-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
44 lines (37 loc) · 1.07 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package rpc
import (
"encoding/json"
"errors"
"fmt"
)
// Response represents the response structure for a Redis RPC call.
type Response struct {
ID string `json:"id"`
Error string `json:"error,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
}
// newResponse creates a new instance of the Response struct.
func NewResponse(id string, result any, err error) (*Response, error) {
if err != nil && result != nil || err == nil && result == nil {
return nil, errors.New("either result or error must be nil")
}
if err != nil {
return &Response{
ID: id,
Error: err.Error(),
}, nil
}
encodedResult, err := json.Marshal(result)
if err != nil {
return nil, fmt.Errorf("error marshalling result: %w", err)
}
return &Response{
ID: id,
Result: encodedResult,
}, nil
}
// ParseResut parses the result of the response into the provided value.
// The result is expected to be in JSON format and will be unmarshaled into the provided value.
func (r *Response) ParseResut(v interface{}) error {
return json.Unmarshal(r.Result, v)
}