From fdd66ab6d160b95d7eb5f2f34cda2f8bc870aa54 Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Tue, 18 Jun 2019 15:20:38 +0200 Subject: [PATCH] docs/customizingyourgateway: add ?pretty example As discussed in slack. The code is rough, but should illustrate the point. Signed-off-by: Stephan Renatus --- docs/_docs/customizingyourgateway.md | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/docs/_docs/customizingyourgateway.md b/docs/_docs/customizingyourgateway.md index 31b7794bd55..8c28ceaca3c 100644 --- a/docs/_docs/customizingyourgateway.md +++ b/docs/_docs/customizingyourgateway.md @@ -28,6 +28,43 @@ The protocol buffer compiler generates camelCase JSON tags that can be used with mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{OrigName:false})) ``` +### Pretty-print JSON responses when queried with ?pretty + +You can have Elasticsearch-style `?pretty` support in your gateway's endpoints as follows: + +1. Wrap the ServeMux using a stdlib [`http.HandlerFunc`](https://golang.org/pkg/net/http/#HandlerFunc) + that translates the provided query parameter into a custom `Accept` header, and +2. Register a pretty-printing marshaller for that MIME code. + +For example: + +```go +mux := runtime.NewServeMux( + runtime.WithMarshalerOption("application/json+pretty", &runtime.JSONPb{Indent: " "}), + ) +prettier := func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer h.ServeHTTP(w, r) + // if the "Accept" is set and NOT */* (sent by curl), keep it as-is + if accept := r.Header.Get("Accept"); accept != "" && accept != "*/*" { + return + } + // checking Values as map[string][]string also catches ?pretty and ?pretty= + // r.URL.Query().Get("pretty") would not. + if _, ok := r.URL.Query()["pretty"]; ok { + r.Header.Set("Accept", "application/json+pretty") + } + }) +} +http.ListenAndServe(":8080", prettier(mux)) +``` + +Now, either when passing the header `Accept: application/json+pretty` or appending `?pretty` to +your HTTP endpoints, the response will be pretty-printed. + +Note that this will conflict with any methods having input messages with fields named `pretty`; +also, this example code does not remove the query parameter `pretty` from further processing. + ## Mapping from HTTP request headers to gRPC client metadata You might not like [the default mapping rule](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#DefaultHeaderMatcher) and might want to pass through all the HTTP headers, for example.