Skip to content

Instantly share code, notes, and snippets.

@MilosSimic
Forked from cep21/ctx_middleware_chain.go
Created November 26, 2019 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MilosSimic/3ecdb763f1e0f8970ccd21b864a8763e to your computer and use it in GitHub Desktop.
Save MilosSimic/3ecdb763f1e0f8970ccd21b864a8763e 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment