Skip to content

Commit

Permalink
🧹 expose HttpError function to allow custom mux implementations to re…
Browse files Browse the repository at this point in the history
…-use it (#15)

Signed-off-by: Christoph Hartmann <[email protected]>
  • Loading branch information
chris-rock authored Jul 29, 2022
1 parent b064470 commit 6d93e9c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
4 changes: 2 additions & 2 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
"google.golang.org/protobuf/proto"
)

// httpError writes an error to the response.
func httpError(w http.ResponseWriter, req *http.Request, err error) {
// HttpError writes an error to the response.
func HttpError(w http.ResponseWriter, req *http.Request, err error) {
// check if the accept header is set, otherwise use the incoming content type
accept := determineResponseType(req.Header.Get("Content-Type"), req.Header.Get("Accept"))

Expand Down
12 changes: 6 additions & 6 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// verify content type
err := verifyContentType(req, contentType)
if err != nil {
httpError(w, req, err)
HttpError(w, req, err)
return
}

if !strings.HasPrefix(req.URL.Path, s.prefix) {
httpError(w, req, status.Error(codes.NotFound, req.URL.Path+" is not available"))
HttpError(w, req, status.Error(codes.NotFound, req.URL.Path+" is not available"))
return
}

Expand All @@ -77,21 +77,21 @@ func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
method, ok := s.service.Methods[name]
if !ok {
err := status.Error(codes.NotFound, "method not defined")
httpError(w, req, err)
HttpError(w, req, err)
return
}

rctx, rcancel, body, err := preProcessRequest(ctx, req)
if err != nil {
httpError(w, req, err)
HttpError(w, req, err)
return
}
defer rcancel()

// invoke method and send the response
resp, err := method(rctx, &body)
if err != nil {
httpError(w, req, err)
HttpError(w, req, err)
return
}
// check if the accept header is set, otherwise use the incoming content type
Expand Down Expand Up @@ -122,7 +122,7 @@ func preProcessRequest(ctx context.Context, req *http.Request) (context.Context,
func (s *server) sendResponse(w http.ResponseWriter, req *http.Request, resp proto.Message, contentType string) {
payload, contentType, err := convertProtoToPayload(resp, contentType)
if err != nil {
httpError(w, req, status.Error(codes.Internal, "error encoding response"))
HttpError(w, req, status.Error(codes.Internal, "error encoding response"))
return
}

Expand Down

0 comments on commit 6d93e9c

Please sign in to comment.