Created
December 15, 2020 10:07
-
-
Save peternoordijk/b444b457323026d82a149737adcdaed5 to your computer and use it in GitHub Desktop.
Basic golang mux router with middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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