-
-
Save MilosSimic/3ecdb763f1e0f8970ccd21b864a8763e to your computer and use it in GitHub Desktop.
Example of using context.Value() as a middleware chain
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
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