Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2016 23:32
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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