return func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "name", "jong")
if ctx.Value("name") != r.URL.Query().Get("name") {
log.Println("You are a Guest")
return
}
rCtx := r.WithContext(ctx)
next.ServeHTTP(w, rCtx)
}
}
func secondLoggingTime(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
}
}
func foo(w http.ResponseWriter, r *http.Request) {
if r.Context().Value("name") == "jong" {
log.Println("You are an Admin")
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/foo", firstLoggingTime(secondLoggingTime(foo)))
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", mux)
log.Fatal(err)
}
go context랑 미들웨어 해보고 있는데
궁금한게
미들웨어에 미들웨어에 미들웨어 체인해서 들어가긴 하는데 (first -> second -> foo순)
first에서 context 만들고
second 함수 파라미터에 request도 안넣어줬는데
어떻게 맨 마지막 foo에서 r.context 값을 받는거야???
내가 짜놓고 왜 굴러가는지도 모르겠네
난 바보인가봐..
사용자 리퀘스트에 컨텍스트가 심어져있는거겠지
고를 안해서 확신은 안가지만 네이밍자체가 커넥션별 컨텍스트를 구현하려는거 같은데
그러면 여러 핸들러들이 리퀘스트를 계속 넘겨받는 와중에도 컨텍스트를 유지해야하니까 리퀘스트 객체 자체에 컨텍스트를 넣어야할듯
글쓴인데 답변 고마워!! 고랭 한글 자료가 없어서 넘 힘들다 + ㅠㅠ