Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using context.Value() as a middleware chain
package goexperiments
import (
"context"
"net/http"
)
type HandlerMiddleware interface {
HandleHTTPC(ctx context.Context, rw http.ResponseWriter, req *http.Request, next http.Handler)
}
var function1 HandlerMiddleware = nil
var function2 HandlerMiddleware = nil
func addUserID(rw http.ResponseWriter, req *http.Request, next http.Handler) {
ctx := context.WithValue(req.Context(), "userid", req.Header.Get("userid"))
req = req.WithContext(ctx)
next.ServeHTTP(rw, req)
}
func useUserID(rw http.ResponseWriter, req *http.Request, next http.Handler) {
uid := req.Context().Value("userid")
rw.Write([]byte(uid))
}
func makeChain(chain ...HandlerMiddleware) http.Handler {return nil}
type Server struct {}
func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
req = req.WithContext(context.Background())
chain := makeChain(addUserID, function1, function2, useUserID)
chain.ServeHTTP(rw, req)
}
@gaorong

This comment has been minimized.

Copy link

@gaorong gaorong commented Apr 21, 2018

req = req.WithContext(context.Background()) need't set the request's initial context explicitly, cause default is context.Background().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.