Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use error value for bad URI so custom error handler could treat it special #932

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions runtime/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ import (
// A HandlerFunc handles a specific pair of path pattern and HTTP method.
type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)

// ErrUnknownURI is the error supplied to a custom ProtoErrorHandlerFunc when
// a request is received with a URI path that does not match any registered
// service method.
//
// Since gRPC servers return an "Unimplemented" code for requests with an
// unrecognized URI path, this error also has a gRPC "Unimplemented" code.
var ErrUnknownURI = status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))

// ServeMux is a request multiplexer for grpc-gateway.
// It matches http requests to patterns and invokes the corresponding handler.
type ServeMux struct {
Expand Down Expand Up @@ -174,8 +182,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if idx := strings.LastIndex(components[l-1], ":"); idx == 0 {
if s.protoErrorHandler != nil {
_, outboundMarshaler := MarshalerForRequest(s, r)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI)
} else {
OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
Expand Down Expand Up @@ -235,8 +242,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if s.protoErrorHandler != nil {
_, outboundMarshaler := MarshalerForRequest(s, r)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusMethodNotAllowed))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI)
} else {
OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
}
Expand All @@ -246,8 +252,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {

if s.protoErrorHandler != nil {
_, outboundMarshaler := MarshalerForRequest(s, r)
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI)
} else {
OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
Expand Down
57 changes: 57 additions & 0 deletions runtime/mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@ package runtime_test

import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func TestMuxServeHTTP(t *testing.T) {
Expand All @@ -29,6 +32,7 @@ func TestMuxServeHTTP(t *testing.T) {
respContent string

disablePathLengthFallback bool
errHandler runtime.ProtoErrorHandlerFunc
}{
{
patterns: nil,
Expand Down Expand Up @@ -239,11 +243,46 @@ func TestMuxServeHTTP(t *testing.T) {
respStatus: http.StatusOK,
respContent: "GET /foo/{id=*}:verb",
},
{
// mux identifying invalid path results in 'Not Found' status
// (with custom handler looking for ErrUnknownURI)
patterns: []stubPattern{
{
method: "GET",
ops: []int{int(utilities.OpLitPush), 0},
pool: []string{"unimplemented"},
},
},
reqMethod: "GET",
reqPath: "/foobar",
respStatus: http.StatusNotFound,
respContent: "GET /foobar",
errHandler: unknownPathIs404,
},
{
// server returning unimplemented results in 'Not Implemented' code
// even when using custom error handler
patterns: []stubPattern{
{
method: "GET",
ops: []int{int(utilities.OpLitPush), 0},
pool: []string{"unimplemented"},
},
},
reqMethod: "GET",
reqPath: "/unimplemented",
respStatus: http.StatusNotImplemented,
respContent: `GET /unimplemented`,
errHandler: unknownPathIs404,
},
} {
var opts []runtime.ServeMuxOption
if spec.disablePathLengthFallback {
opts = append(opts, runtime.WithDisablePathLengthFallback())
}
if spec.errHandler != nil {
opts = append(opts, runtime.WithProtoErrorHandler(spec.errHandler))
}
mux := runtime.NewServeMux(opts...)
for _, p := range spec.patterns {
func(p stubPattern) {
Expand All @@ -252,6 +291,13 @@ func TestMuxServeHTTP(t *testing.T) {
t.Fatalf("runtime.NewPattern(1, %#v, %#v, %q) failed with %v; want success", p.ops, p.pool, p.verb, err)
}
mux.Handle(p.method, pat, func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
if r.URL.Path == "/unimplemented" {
// simulate method returning "unimplemented" error
_, m := runtime.MarshalerForRequest(mux, r)
runtime.HTTPError(r.Context(), mux, m, w, r, status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)))
w.WriteHeader(http.StatusNotImplemented)
return
}
fmt.Fprintf(w, "%s %s", p.method, pat.String())
})
}(p)
Expand Down Expand Up @@ -279,6 +325,17 @@ func TestMuxServeHTTP(t *testing.T) {
}
}

func unknownPathIs404(ctx context.Context, mux *runtime.ServeMux, m runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
if err == runtime.ErrUnknownURI {
w.WriteHeader(http.StatusNotFound)
} else {
c := status.Convert(err).Code()
w.WriteHeader(runtime.HTTPStatusFromCode(c))
}

fmt.Fprintf(w, "%s %s", r.Method, r.URL.Path)
}

var defaultHeaderMatcherTests = []struct {
name string
in string
Expand Down