From 259e65cd518a0b54e48515f927f46e6ff97f79f8 Mon Sep 17 00:00:00 2001 From: Julian Dolce Date: Fri, 2 Feb 2018 12:08:24 -0500 Subject: [PATCH] HTTP server NoOpRequestDecoder Adds NoOpRequestDecoder for HTTP request that do not need to be decoded. Fixes #657 --- transport/http/server.go | 6 ++++++ transport/http/server_test.go | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/transport/http/server.go b/transport/http/server.go index 13a27d958..183009d22 100644 --- a/transport/http/server.go +++ b/transport/http/server.go @@ -136,6 +136,12 @@ type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter) // provided in the context under keys with the ContextKeyResponse prefix. type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request) +// NopRequestDecoder is a DecodeRequestFunc that can be used for requests that do not +// need to be decoded, and simply returns nil, nil. +func NopRequestDecoder(ctx context.Context, r *http.Request) (interface{}, error) { + return nil, nil +} + // EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a // JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as // a sensible default. If the response implements Headerer, the provided headers diff --git a/transport/http/server_test.go b/transport/http/server_test.go index 20a077811..c4359272e 100644 --- a/transport/http/server_test.go +++ b/transport/http/server_test.go @@ -393,6 +393,28 @@ func TestEnhancedError(t *testing.T) { } } +func TestNoOpRequestDecoder(t *testing.T) { + resw := httptest.NewRecorder() + req, err := http.NewRequest(http.MethodGet, "/", nil) + if err != nil { + t.Error("Failed to create request") + } + handler := httptransport.NewServer( + func(ctx context.Context, request interface{}) (interface{}, error) { + if request != nil { + t.Error("Expected nil request in endpoint when using NopRequestDecoder") + } + return nil, nil + }, + httptransport.NopRequestDecoder, + httptransport.EncodeJSONResponse, + ) + handler.ServeHTTP(resw, req) + if resw.Code != http.StatusOK { + t.Errorf("Expected status code %d but got %d", http.StatusOK, resw.Code) + } +} + func testServer(t *testing.T) (step func(), resp <-chan *http.Response) { var ( stepch = make(chan bool)