命令
路由
JWT
- 生成token
func getToken(secreKey string, iat, seconds, userId int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
claims["userId"] = userId
token := jwt.New(jwt.SigningMethodES256)
token.Claims = claims
return token.SignedString([]byte(secreKey))
}
- 启动中间件
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/from/:name",
Handler: UserHandler(serverCtx),
},
},
rest.WithJwt("秘钥"),
)
}
- jwt 传输, 在header 头部
Authorization: Bearer <token>
server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
logc.Infof(context.Background(), "WithUnauthorizedCallback")
}))
- 中间件
// 自定义的中间件
func CorsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-Middleware", "static-middleware")
next(w, r)
}
}
- response 输出格式化
func Response(r *http.Request, w http.ResponseWriter, res any, err error) {
if err != nil {
body := Body{
Code: -1,
Msg: "",
Data: nil,
}
httpx.WriteJson(w, http.StatusOK, body)
return
}
body := Body{
Code: 0,
Msg: "ok",
Data: res,
}
httpx.WriteJson(w, http.StatusOK, body)
}
- 日志
如果不初始化,日志按照默认配置
logx.MustSetup(logx.LogConf{})