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
135 | 135 |
// provided in the context under keys with the ContextKeyResponse prefix.
|
136 | 136 |
type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request)
|
137 | 137 |
|
|
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 |
|
138 | 144 |
// EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a
|
139 | 145 |
// JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as
|
140 | 146 |
// a sensible default. If the response implements Headerer, the provided headers
|
389 | 389 |
buf, _ := ioutil.ReadAll(resp.Body)
|
390 | 390 |
if want, have := `{"err":"enhanced"}`, strings.TrimSpace(string(buf)); want != have {
|
391 | 391 |
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)
|
392 | 414 |
}
|
393 | 415 |
}
|
394 | 416 |
|