Skip to content

Instantly share code, notes, and snippets.

@joaoh82
Created June 22, 2019 22:59
Show Gist options
  • Save joaoh82/f8d341ff2f85ddcca3dd22bf3e12ce7c to your computer and use it in GitHub Desktop.
Save joaoh82/f8d341ff2f85ddcca3dd22bf3e12ce7c to your computer and use it in GitHub Desktop.
package gocontext
import (
"context"
"net/http"
)
type SomeMiddleware interface {
HandleHTTPC(ctx context.Context, rw http.ResponseWriter, req *http.Request, next http.Handler)
}
var functionA SomeMiddleware = nil
var functionB SomeMiddleware = 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 ...SomeMiddleware) 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, functionA, functionB, useUserID)
chain.ServeHTTP(rw, req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment