Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Golang net/http Context and Dependency Injection
package main
import (
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.Write([]byte("No message provided."))
} else {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment