1package mux_test 2 3import ( 4 "log" 5 "net/http" 6 7 "github.com/gorilla/mux" 8) 9 10// Define our struct 11type authenticationMiddleware struct { 12 tokenUsers map[string]string 13} 14 15// Initialize it somewhere 16func (amw *authenticationMiddleware) Populate() { 17 amw.tokenUsers["00000000"] = "user0" 18 amw.tokenUsers["aaaaaaaa"] = "userA" 19 amw.tokenUsers["05f717e5"] = "randomUser" 20 amw.tokenUsers["deadbeef"] = "user0" 21} 22 23// Middleware function, which will be called for each request 24func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { 25 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 26 token := r.Header.Get("X-Session-Token") 27 28 if user, found := amw.tokenUsers[token]; found { 29 // We found the token in our map 30 log.Printf("Authenticated user %s\n", user) 31 next.ServeHTTP(w, r) 32 } else { 33 http.Error(w, "Forbidden", http.StatusForbidden) 34 } 35 }) 36} 37 38func Example_authenticationMiddleware() { 39 r := mux.NewRouter() 40 r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 41 // Do something here 42 }) 43 amw := authenticationMiddleware{make(map[string]string)} 44 amw.Populate() 45 r.Use(amw.Middleware) 46} 47