Documentation
¶
Overview ¶
Package grpcutil holds the servicekit/http helpers that understand gRPC status errors: mapping a status code to an HTTP status, writing a JSON error body or WebSocket error frame that carries the code.
They live here rather than in servicekit/http so that a JSON-only server doesn't link google.golang.org/grpc (issue 17). Until v0.2.0 they were gohttp.SendJsonResponse, gohttp.ErrorToHttpCode, gohttp.WSConnWriteError and gohttp.WSConnJSONReaderWriter, with the same behaviour.
Index ¶
- func ErrorToHTTPCode(err error) int
- func SendJSONResponse(writer http.ResponseWriter, resp any, err error)
- func WSConnJSONReaderWriter(conn *websocket.Conn) (reader *conc.Reader[gut.StrMap], writer *conc.Writer[conc.Message[gut.StrMap]])
- func WSConnWriteError(wsConn *websocket.Conn, err error) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ErrorToHTTPCode ¶
ErrorToHTTPCode converts a Go error to an appropriate HTTP status code. If err is nil, returns http.StatusOK (200). If err contains a gRPC status, maps it to the corresponding HTTP code:
- codes.PermissionDenied → 403 Forbidden
- codes.NotFound → 404 Not Found
- codes.AlreadyExists → 409 Conflict
- codes.InvalidArgument → 400 Bad Request
- Other errors → 500 Internal Server Error
func SendJSONResponse ¶
func SendJSONResponse(writer http.ResponseWriter, resp any, err error)
SendJSONResponse writes a JSON response to the http.ResponseWriter. If err is nil, resp is marshaled to JSON and written with status 200 OK. If err is non-nil, an appropriate HTTP error code is set based on the gRPC status code (if present), and an error object is returned in the response body.
The function handles gRPC status errors by extracting the code and message, and maps them to appropriate HTTP status codes via ErrorToHTTPCode.
func WSConnJSONReaderWriter ¶
func WSConnJSONReaderWriter(conn *websocket.Conn) (reader *conc.Reader[gut.StrMap], writer *conc.Writer[conc.Message[gut.StrMap]])
WSConnJSONReaderWriter creates concurrent reader and writer for JSON messages over a WebSocket connection. The reader decodes incoming JSON messages into StrMap (map[string]any), and the writer sends outgoing StrMap messages as JSON.
The reader handles connection close errors gracefully by converting them to net.ErrClosed. The writer handles io.EOF as a normal stream end and uses WSConnWriteError for error messages.
This is useful for creating bidirectional JSON message streams over WebSocket.
func WSConnWriteError ¶
WSConnWriteError writes an error message to a WebSocket connection. If err is nil or io.EOF, no message is sent and nil is returned. For gRPC status errors, the error code is extracted and sent as JSON. The message is sent as a text frame containing JSON: {"error": <code>}
Types ¶
This section is empty.