github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/mux/example_authentication_middleware_test.go (about)

     1  package mux_test
     2  
     3  import (
     4  	"log"
     5  
     6  	http "github.com/hxx258456/ccgo/gmhttp"
     7  	"github.com/hxx258456/ccgo/mux"
     8  )
     9  
    10  // Define our struct
    11  type authenticationMiddleware struct {
    12  	tokenUsers map[string]string
    13  }
    14  
    15  // Initialize it somewhere
    16  func (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
    24  func (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  
    38  func 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  }