Skip to content

Commit 514757d

Browse files
authored
Fix customizing your gateway documentation CustomMatcher example (grpc-ecosystem#1142)
* Fix customizing your gateway documentation CustomMatcher example * Add more documentation about mapping from HTTP request headers to gRPC client metadata
1 parent b703778 commit 514757d

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

docs/_docs/customizingyourgateway.md

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@ You might not like [the default mapping rule](http://godoc.org/github.com/grpc-e
8787
```go
8888
func CustomMatcher(key string) (string, bool) {
8989
switch key {
90-
case "x-custom-header1":
90+
case "X-Custom-Header1":
9191
return key, true
92-
case "x-custom-header2":
92+
case "X-Custom-Header2":
9393
return "custom-header2", true
9494
default:
9595
return key, false
@@ -98,8 +98,39 @@ You might not like [the default mapping rule](http://godoc.org/github.com/grpc-e
9898
...
9999

100100
mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(CustomMatcher))
101-
102101
```
102+
To keep the [the default mapping rule](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#DefaultHeaderMatcher) alongside with your own rules write:
103+
104+
```go
105+
func CustomMatcher(key string) (string, bool) {
106+
switch key {
107+
case "X-User-Id":
108+
return key, true
109+
default:
110+
return runtime.DefaultHeaderMatcher(key)
111+
}
112+
}
113+
```
114+
It will work with both:
115+
116+
```bash
117+
curl --header "x-user-id: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...
118+
```
119+
and:
120+
```bash
121+
curl --header "X-USER-ID: 100d9f38-2777-4ee2-ac3b-b3a108f81a30" ...
122+
```
123+
To access this header on gRPC server side use:
124+
```go
125+
...
126+
userID := ""
127+
if md, ok := metadata.FromIncomingContext(ctx); ok {
128+
if uID, ok := md["x-user-id"]; ok {
129+
userID = strings.Join(uID, ",")
130+
}
131+
}
132+
...
133+
```
103134

104135
## Mapping from gRPC server metadata to HTTP response headers
105136
ditto. Use [`WithOutgoingHeaderMatcher`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithOutgoingHeaderMatcher).

0 commit comments

Comments
 (0)