-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
transport/http: PopulateRequestContext
This RequestFunc moves many HTTP request parameters to the context under specific keys. If wired in to the transport, those values are available to subsequent endpoints or service methods that receive the context. This can be used to e.g. log transport (HTTP) details in a service logging middleware.
- Loading branch information
1 parent
520cf55
commit b608fa9
Showing
2 changed files
with
117 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package http | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"net/http/httptest" | ||
|
||
"golang.org/x/net/context" | ||
) | ||
|
||
func ExamplePopulateRequestContext() { | ||
handler := NewServer( | ||
context.Background(), | ||
func(ctx context.Context, request interface{}) (response interface{}, err error) { | ||
fmt.Println("Method", ctx.Value(ContextKeyRequestMethod).(string)) | ||
fmt.Println("RequestPath", ctx.Value(ContextKeyRequestPath).(string)) | ||
fmt.Println("RequestURI", ctx.Value(ContextKeyRequestURI).(string)) | ||
fmt.Println("X-Request-ID", ctx.Value(ContextKeyRequestXRequestID).(string)) | ||
return struct{}{}, nil | ||
}, | ||
func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil }, | ||
func(context.Context, http.ResponseWriter, interface{}) error { return nil }, | ||
ServerBefore(PopulateRequestContext), | ||
) | ||
|
||
server := httptest.NewServer(handler) | ||
defer server.Close() | ||
|
||
req, _ := http.NewRequest("PATCH", fmt.Sprintf("%s/search?q=sympatico", server.URL), nil) | ||
req.Header.Set("X-Request-Id", "a1b2c3d4e5") | ||
http.DefaultClient.Do(req) | ||
|
||
// Output: | ||
// Method PATCH | ||
// RequestPath /search | ||
// RequestURI /search?q=sympatico | ||
// X-Request-ID a1b2c3d4e5 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters