package main import ( "context" "encoding/json" "fmt" "net/http" "strings" "github.com/gorilla/mux" ) const secret = "secret" type DefaultClaims struct { UserID uint `json:"user_id"` RoleType string `json:"role_type"` } func main() { router := mux.NewRouter() router.HandleFunc("/", Authorizate(DefaultHandler, secret)).Methods("POST") http.ListenAndServe(":8090", router) } func DefaultHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) d, ok := r.Context().Value("defaultClaims").(DefaultClaims) if !ok { fmt.Println("doesn't has the key user_id") } fmt.Printf("UserID: %d, role: %s\n", d.UserID, d.RoleType) json.NewEncoder(w).Encode(map[string]string{ "message": "OK", }) } func Authorizate(next http.HandlerFunc, secret string) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := strings.Split(r.Header.Get("Authorization"), " ") token := authHeader[len(authHeader)-1] // validateToken must return a 'token.DefaultClaims' and bool if validateToken(token, secret) { ctx := r.Context() d := DefaultClaims{ UserID: 123, RoleType: "SUPPORT", } ctx = context.WithValue(ctx, "defaultClaims", d) next.ServeHTTP(w, r.WithContext(ctx)) } else { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusForbidden) json.NewEncoder(w).Encode(map[string]string{ "message": "Forbidden", }) } }) } func validateToken(token, secret string) bool { // check if is a valid the [user|service] token using secret return true }