Skip to content

Instantly share code, notes, and snippets.

@squirly
Created July 11, 2016 23:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squirly/4bd9dbd0a7d78d03b9527bdf4d0abeff to your computer and use it in GitHub Desktop.
Save squirly/4bd9dbd0a7d78d03b9527bdf4d0abeff to your computer and use it in GitHub Desktop.
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