You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

47 lines
1.1 KiB

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