Skip to content

Commit

Permalink
Expose HTTP method in unary handlers
Browse files Browse the repository at this point in the history
Fixes #502 to expose the HTTP method in handlers.
  • Loading branch information
akshayjshah committed May 17, 2023
1 parent 17eb88d commit b6ff498
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 1 addition & 1 deletion client_ext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ type notModifiedPingServer struct {
func (s *notModifiedPingServer) Ping(
_ context.Context,
req *connect.Request[pingv1.PingRequest]) (*connect.Response[pingv1.PingResponse], error) {
if len(req.Peer().Query) > 0 && req.Header().Get("If-None-Match") == s.etag {
if req.HTTPMethod() == http.MethodGet && req.Header().Get("If-None-Match") == s.etag {
return nil, connect.NewNotModifiedError(http.Header{"Etag": []string{s.etag}})
}
resp := connect.NewResponse(&pingv1.PingResponse{})
Expand Down
16 changes: 7 additions & 9 deletions error_not_modified_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,14 @@ func (*ExampleCachingPingServer) Ping(
})
// Our hashing logic is simple: we use the number in the PingResponse.
hash := fmt.Sprint(resp.Msg.Number)
// If the request was an HTTP GET (which always has URL query parameters),
// we'll need to check if the client already has the response cached.
if len(req.Peer().Query) > 0 {
if req.Header().Get("If-None-Match") == hash {
return nil, connect.NewNotModifiedError(http.Header{
"Etag": []string{hash},
})
}
resp.Header().Set("Etag", hash)
// If the request was an HTTP GET, we'll need to check if the client already
// has the response cached.
if req.HTTPMethod() == http.MethodGet && req.Header().Get("If-None-Match") == hash {
return nil, connect.NewNotModifiedError(http.Header{
"Etag": []string{hash},
})
}
resp.Header().Set("Etag", hash)
return resp, nil
}

Expand Down
7 changes: 7 additions & 0 deletions protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,13 @@ func (hc *errorTranslatingHandlerConnCloser) Close(err error) error {
return hc.fromWire(closeErr)
}

func (hc *errorTranslatingHandlerConnCloser) getHTTPMethod() string {
if methoder, ok := hc.handlerConnCloser.(interface{ getHTTPMethod() string }); ok {
return methoder.getHTTPMethod()
}
return http.MethodPost
}

// errorTranslatingClientConn wraps a StreamingClientConn to make sure that we always
// return coded errors from clients.
//
Expand Down

0 comments on commit b6ff498

Please sign in to comment.