Skip to content

Instantly share code, notes, and snippets.

@cep21
Last active July 25, 2022 10:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cep21/a3fc8e1462d19c46422c03b0466d5869 to your computer and use it in GitHub Desktop.
Save cep21/a3fc8e1462d19c46422c03b0466d5869 to your computer and use it in GitHub Desktop.
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
Copy link

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