Golang net/http Context and Dependency Injection
package main | |
import ( | |
"context" | |
"net/http" | |
) | |
func main() { | |
helloHandler := AddMessageMiddleware("Hello!", http.HandlerFunc(RespondWithMessage)) | |
goodbyeHandler := AddMessageMiddleware("Goodbye!", http.HandlerFunc(RespondWithMessage)) | |
noMessageHandler := http.HandlerFunc(RespondWithMessage) | |
mux := new(http.ServeMux) | |
mux.Handle("/hello", helloHandler) | |
mux.Handle("/goodbye", goodbyeHandler) | |
mux.Handle("/error", noMessageHandler) | |
http.ListenAndServe(":8000", mux) | |
} | |
const MessageContextKey = "message" | |
func AddMessageMiddleware(message string, next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
ctx := context.WithValue(r.Context(), MessageContextKey, message) | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
}) | |
} | |
func RespondWithMessage(w http.ResponseWriter, r *http.Request) { | |
message := r.Context().Value(MessageContextKey) | |
if message == nil { | |
w.WriteHeader(500) | |
w.Write([]byte("No message provided.")) | |
} else { | |
w.WriteHeader(200) | |
w.Write([]byte(message.(string))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment