Last active
July 25, 2022 10:17
-
-
Save cep21/a3fc8e1462d19c46422c03b0466d5869 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
req = req.WithContext(context.Background())
need't set the request's initial context explicitly, cause default is context.Background().