一个轻量却强大的上下文管理器,一个请求会生成一个context,贯穿整个请求,context记录原始请求上下文,请求时间,客户端信息,权限校验信息,及负责判断是否内部调用, 及附带唯一traceId的日志记录器
import (
stdcontext "context""github.com/hopeio/context"
)
ctx:=context.NewContext(stdcontext.Background())stdctx=ctx.Wrapper()
ctxi,_=context.FromContext(stdctx)import (
"github.com/hopeio/context/httpctx"
)
funcHandle(w http.ResponseWriter, r*http.Request) {
ctx:=httpctx.FromRequest(httpctx.RequestCtx{r,w})
}funcMiddleware(w http.ResponseWriter, r*http.Request) {
ctx:=httpctx.FromRequest(httpctx.RequestCtx{r,w})
r.WithContext(ctx.Wrapper())
}
funcHandle(w http.ResponseWriter, r*http.Request) {
reqctx, ok:=httpctx.FromContext(r.Context())
}import (
"errors""encoding/json""strings""github.com/golang-jwt/jwt/v5""github.com/hopeio/context/httpctx"
)
vartokenSecret= []byte("xxx")
typeAuthInfostruct {
Iduint64`json:"id"`
}
typeAuthorizationstruct {
*AuthInfo`json:"auth"`
jwt.RegisteredClaimsAuthInfoRawstring`json:"-"`
}
func (x*Authorization) Validate() error {
returnnil
}
func (x*Authorization) GenerateToken(secret []byte) (string, error) {
tokenClaims:=jwt.NewWithClaims(jwt.SigningMethodHS256, x)
token, err:=tokenClaims.SignedString(secret)
returntoken, err
}
func (x*Authorization) ParseToken(tokenstring, secret []byte) error {
_, err:=jwti.ParseToken(x, token, secret)
iferr!=nil {
returnerr
}
x.ID=x.AuthInfo.IdStr()
authBytes, _:=json.Marshal(x.AuthInfo)
x.AuthInfoRaw=string(authBytes)
returnnil
}
funcGetAuth(ctx*httpctx.Context) (*AuthInfo, error) {
signature:=ctx.Token[strings.LastIndexByte(ctx.Token, '.')+1:]
authorization:=Authorization{AuthInfo: &AuthInfo{}}
iferr:=authorization.ParseToken(ctx.Token, tokenSecret); err!=nil {
returnnil, err
}
authInfo:=authorization.AuthInfoctx.AuthID=authInfo.IdStr()
ctx.AuthInfo=authInfoctx.AuthInfoRaw=authorization.AuthInfoRawreturnauthInfo, nil
}