Codebase list golang-github-go-kit-kit / 321a6f5
HTTP server NoOpRequestDecoder (#659) Adds NoOpRequestDecoder for HTTP request that do not need to be decoded. Fixes #657 Julian Dolce authored 6 years ago Peter Bourgon committed 6 years ago
2 changed file(s) with 28 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
135135 // provided in the context under keys with the ContextKeyResponse prefix.
136136 type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request)
137137
138 // NopRequestDecoder is a DecodeRequestFunc that can be used for requests that do not
139 // need to be decoded, and simply returns nil, nil.
140 func NopRequestDecoder(ctx context.Context, r *http.Request) (interface{}, error) {
141 return nil, nil
142 }
143
138144 // EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a
139145 // JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as
140146 // a sensible default. If the response implements Headerer, the provided headers
389389 buf, _ := ioutil.ReadAll(resp.Body)
390390 if want, have := `{"err":"enhanced"}`, strings.TrimSpace(string(buf)); want != have {
391391 t.Errorf("Body: want %s, have %s", want, have)
392 }
393 }
394
395 func TestNoOpRequestDecoder(t *testing.T) {
396 resw := httptest.NewRecorder()
397 req, err := http.NewRequest(http.MethodGet, "/", nil)
398 if err != nil {
399 t.Error("Failed to create request")
400 }
401 handler := httptransport.NewServer(
402 func(ctx context.Context, request interface{}) (interface{}, error) {
403 if request != nil {
404 t.Error("Expected nil request in endpoint when using NopRequestDecoder")
405 }
406 return nil, nil
407 },
408 httptransport.NopRequestDecoder,
409 httptransport.EncodeJSONResponse,
410 )
411 handler.ServeHTTP(resw, req)
412 if resw.Code != http.StatusOK {
413 t.Errorf("Expected status code %d but got %d", http.StatusOK, resw.Code)
392414 }
393415 }
394416