Implement RPC

This commit is contained in:
Samuel Lorch 2024-04-28 01:58:45 +02:00
parent 9699582d72
commit 496d5f412f
6 changed files with 289 additions and 0 deletions

41
rpc/error.go Normal file
View file

@ -0,0 +1,41 @@
package rpc
import (
"context"
"encoding/json"
"log/slog"
"nhooyr.io/websocket"
)
func respondError(ctx context.Context, c *websocket.Conn, id string, code int64, err error, data any) {
slog.ErrorContext(ctx, "Responding to Websocket Request With Error", "err", err, "id", id, "code", code, "data", data)
rData := []byte{}
if data != nil {
rData, err = json.Marshal(data)
if err != nil {
slog.ErrorContext(ctx, "Error Marshalling Error Data", "err", err)
return
}
}
raw := json.RawMessage(rData)
resp, err := json.Marshal(Response{
ID: id,
Error: &Error{
Code: code,
Message: err.Error(),
Data: &raw,
},
})
if err != nil {
slog.ErrorContext(ctx, "Error Marshalling Error Response", "err", err)
return
}
err = c.Write(ctx, websocket.MessageText, resp)
if err != nil {
slog.ErrorContext(ctx, "Error Sending Error Response", "err", err)
return
}
}