Skip to content

v1.3.6

Choose a tag to compare

@ixugo ixugo released this 21 Aug 04:41
  1. web.WarpHs 支持包装中间件
  2. 重构 jwt,改动了签名,与旧版本不兼容
  3. 优化 conf.WriteConfig 函数回写配置
  4. web.LoggerWithUseTime() 记录耗时请求

jwt 新的调用方式

// 创建 token
data := NewClaimsData().SetUsername("admin")
token, _ := NewToken( data,  "secret",  web.WithExpiresAt( time.Now().Add( time.Hour) ) )
// 中间件
auth := AuthMiddleware( "secret" )
gin.Get("/users", auth,  getUser)
// 业务中获取 token 里设置的参数
func getUser(c *gin.Context) {
 username := web.GetUsername(c)
}

jwt 中没有预设的参数时,可以 NewClaimsData().Set( "key", "value" ),在业务中获取 c.Get("key")

最佳实践是建议定义 key 为常量,设置和获取的时使用常量,如下

const contextKeyUser = "user"
// 发放 token 的时设置
NewClaimsData().Set(  contextKeyUser , "value" )
// 业务中获取
func user(c *gin.Context) {
   u := GetUser(c)
}