Write responses as byte
(errMsg string, x any)
| 370 | |
| 371 | // Write responses as byte |
| 372 | func (c *ServerCodec) Write(errMsg string, x any) ([]byte, error) { |
| 373 | // If return error: nothing happens. |
| 374 | // In r.Error will be "" or .Error() of error returned by: |
| 375 | // - ReadBody() |
| 376 | // - called RPC method |
| 377 | resp := serverResponse{Version: Version, ID: c.req.ID, Result: x} |
| 378 | if len(errMsg) == 0 { |
| 379 | if x == nil { |
| 380 | resp.Result = &null |
| 381 | } else { |
| 382 | resp.Result = x |
| 383 | } |
| 384 | } else if errMsg[0] == '{' && errMsg[len(errMsg)-1] == '}' { |
| 385 | // Well& this check for '{'&'}' isn't too strict, but I |
| 386 | // suppose we're trusting our own RPC methods (this way they |
| 387 | // can force sending wrong reply or many replies instead |
| 388 | // of one) and normal errors won't be formatted this way. |
| 389 | raw := json.RawMessage(errMsg) |
| 390 | resp.Error = &raw |
| 391 | } else { |
| 392 | raw := json.RawMessage(newError(errMsg).Error()) |
| 393 | resp.Error = &raw |
| 394 | } |
| 395 | |
| 396 | buf := bytes.NewBuffer(nil) |
| 397 | defer buf.Reset() |
| 398 | enc := json.NewEncoder(buf) |
| 399 | if err := enc.Encode(resp); err != nil { |
| 400 | return nil, perrors.WithStack(err) |
| 401 | } |
| 402 | |
| 403 | return buf.Bytes(), nil |
| 404 | } |