Skip to content

Commit

Permalink
docs/customizingyourgateway: add ?pretty example
Browse files Browse the repository at this point in the history
As discussed in slack. The code is rough, but should illustrate the
point.

Signed-off-by: Stephan Renatus <[email protected]>
  • Loading branch information
srenatus committed Jun 18, 2019
1 parent cd0c8ef commit 503e4af
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions docs/_docs/customizingyourgateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`](#TODO) 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.
Expand Down

0 comments on commit 503e4af

Please sign in to comment.