Skip to content

Instantly share code, notes, and snippets.

@peternoordijk
Created December 15, 2020 10:07
Show Gist options
  • Save peternoordijk/b444b457323026d82a149737adcdaed5 to your computer and use it in GitHub Desktop.
Save peternoordijk/b444b457323026d82a149737adcdaed5 to your computer and use it in GitHub Desktop.
Basic golang mux router with middleware
package main
import (
"context"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type messageKey struct{}
func myMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req := r.WithContext(context.WithValue(ctx, messageKey{}, "hello world"))
next.ServeHTTP(w, req)
})
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if message, ok := ctx.Value(messageKey{}).(string); ok {
fmt.Fprintf(w, "The message is '%s'", message)
} else {
fmt.Fprintf(w, "No message received :(")
}
}
func main() {
r := mux.NewRouter()
r.Use(myMiddleware)
r.HandleFunc("/hi", handler).Methods("GET")
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":5000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment