init project
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
ReqInfoKey reqInfoKeyType = "request-info"
|
||||
)
|
||||
|
||||
func SetTraceId(c *gin.Context, traceId string) {
|
||||
info, exists := c.Get(ReqInfoKey)
|
||||
if exists {
|
||||
parsedInfo := info.(RequestInfo)
|
||||
parsedInfo.TraceId = traceId
|
||||
|
||||
c.Set(ReqInfoKey, parsedInfo)
|
||||
|
||||
return
|
||||
}
|
||||
c.Set(ReqInfoKey, RequestInfo{TraceId: traceId})
|
||||
}
|
||||
|
||||
func SetUserId(c *gin.Context, userId int64) {
|
||||
info, exists := c.Get(ReqInfoKey)
|
||||
if exists {
|
||||
parsedInfo := info.(RequestInfo)
|
||||
parsedInfo.UserId = userId
|
||||
|
||||
c.Set(ReqInfoKey, parsedInfo)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(ReqInfoKey, RequestInfo{UserId: userId})
|
||||
}
|
||||
|
||||
func SetUserContext(c *gin.Context, payload map[string]interface{}) {
|
||||
c.Set(ReqInfoKey, RequestInfo{
|
||||
UserId: int64(payload["userId"].(float64)),
|
||||
Role: payload["role"].(string),
|
||||
})
|
||||
}
|
||||
|
||||
func ContextWithReqInfo(c *gin.Context) context.Context {
|
||||
info, ok := c.Get(ReqInfoKey)
|
||||
if ok {
|
||||
return WithRequestInfo(c, info.(RequestInfo))
|
||||
}
|
||||
|
||||
return WithRequestInfo(c, RequestInfo{})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package request
|
||||
|
||||
import "context"
|
||||
|
||||
type requestInfoKey int
|
||||
|
||||
const (
|
||||
key requestInfoKey = iota
|
||||
)
|
||||
|
||||
type RequestInfo struct {
|
||||
UserId int64
|
||||
TraceId string
|
||||
Permissions map[string]bool
|
||||
Role string
|
||||
}
|
||||
|
||||
func WithRequestInfo(ctx context.Context, info RequestInfo) context.Context {
|
||||
return context.WithValue(ctx, key, info)
|
||||
}
|
||||
|
||||
func GetRequestInfo(ctx context.Context) (requestInfo RequestInfo, ok bool) {
|
||||
requestInfo, ok = ctx.Value(key).(RequestInfo)
|
||||
return
|
||||
}
|
||||
|
||||
type reqInfoKeyType = string
|
||||
|
||||
const (
|
||||
reqInfoKey reqInfoKeyType = "request-info"
|
||||
)
|
||||
|
||||
func GetReqInfo(c context.Context) RequestInfo {
|
||||
info := c.Value(reqInfoKey)
|
||||
if info != nil {
|
||||
return info.(RequestInfo)
|
||||
}
|
||||
|
||||
return RequestInfo{}
|
||||
}
|
||||
Reference in New Issue
Block a user