1 Star 0 Fork 0

robertzhai / go_common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gin_ctx.go 970 Bytes
一键复制 编辑 原始数据 按行查看 历史
robertzhai 提交于 2023-06-16 10:28 . init
package middleware
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/nacos-group/nacos-sdk-go/inner/uuid"
)
const (
GIN_CONTEXT_KEY = "GinContextKey"
)
// https://gqlgen.com/recipes/gin/#accessing-gincontext
func GinContextToContextMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), GIN_CONTEXT_KEY, c)
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}
func GinContextFromContext(ctx context.Context) (*gin.Context, error) {
ginContext := ctx.Value(GIN_CONTEXT_KEY)
if ginContext == nil {
err := fmt.Errorf("could not retrieve gin.Context")
return nil, err
}
gc, ok := ginContext.(*gin.Context)
if !ok {
err := fmt.Errorf("gin.Context has wrong type")
return nil, err
}
return gc, nil
}
// cli context
func GetCliCtx() *gin.Context {
rid := ""
if uuidGen != uuid.Nil {
rid = uuidGen.String()
}
ctx := &gin.Context{}
ctx.Set(REQUEST_ID, rid)
return ctx
}
Go
1
https://gitee.com/home_robertzhai/go_common.git
git@gitee.com:home_robertzhai/go_common.git
home_robertzhai
go_common
go_common
v1.1.0

搜索帮助

53164aa7 5694891 3bd8fe86 5694891