player2ctxmiddleware.go 946 B

123456789101112131415161718192021222324252627282930313233
  1. package middleware
  2. import (
  3. "context"
  4. "github.com/golang-jwt/jwt/v4"
  5. "net/http"
  6. "ylink/ext/globalkey"
  7. "ylink/ext/jwtdata"
  8. )
  9. type Player2CtxMiddleware struct {
  10. }
  11. func NewPlayer2CtxMiddleware() *Player2CtxMiddleware {
  12. return &Player2CtxMiddleware{}
  13. }
  14. func (m *Player2CtxMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  15. return func(w http.ResponseWriter, r *http.Request) {
  16. accessToken := r.Header.Get("Authorization")
  17. ctx := r.Context()
  18. token, _ := jwt.Parse(accessToken, func(token *jwt.Token) (i interface{}, err error) {
  19. return []byte(globalkey.AccessSecret), nil
  20. })
  21. // 将获取的token中的Claims强转为MapClaims
  22. claims, _ := token.Claims.(jwt.MapClaims)
  23. playerId := claims[jwtdata.JwtKeyPlayerId]
  24. gameId := claims[jwtdata.JwtKeyGameId]
  25. ctx = context.WithValue(ctx, jwtdata.JwtKeyPlayerId, playerId)
  26. ctx = context.WithValue(ctx, jwtdata.JwtKeyGameId, gameId)
  27. next(w, r.WithContext(ctx))
  28. }
  29. }