.api文件新增middleware,通过goctl api 生成文件以后,记得把文档往下翻一翻,还需要再svc里面加一些配置,然后再生成的文件中写入自己的业务
@server (
prefix: /v1/system
group: system
middleware: AuthInterceptor
)
package middleware
import (
"go/application/internal/config"
redisClient "go/application/sevice/redis"
"go/pkg/jwt"
"net/http"
"time"
)
type AuthInterceptorMiddleware struct {
}
func NewAuthInterceptorMiddleware() *AuthInterceptorMiddleware {
return &AuthInterceptorMiddleware{}
}
// 这个是goctl生成的函数
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// TODO generate middleware implement function, delete after code implementation
authRequest := r.Header.Get("Authorization")
if authRequest == "" {
w.WriteHeader(http.StatusAccepted)
w.Write([]byte("请登录"))
return
}
// Token解密
authParse, authErr := jwt.ParseToken(authRequest, config.GlobalConfig.Auth.AccessSecret)
// 解密失败
if authErr != nil {
w.WriteHeader(http.StatusAccepted)
w.Write([]byte(authErr.Error()))
}
// 初始化redis
redis := redisClient.Init(config.GlobalConfig)
val, redisErr := redis.Get(authParse.UserId).Result()
if redisErr != nil {
w.WriteHeader(http.StatusAccepted)
w.Write([]byte(redisErr.Error()))
return
}
// 查看redis中是否存在该用户id
if val != "" {
// 将用户id作为key,token做为value 重新存入redis 延长该用户token过期时长
redis.Set(val, authRequest, time.Duration(config.GlobalConfig.Auth.AccessExpire))
} else {
w.WriteHeader(http.StatusAccepted)
w.Write([]byte("token已过期"))
return
}
next(w, r)
}
}