提交 0a34ab95 authored 作者: mooncake9527's avatar mooncake9527

cost

上级 d1bd882d
......@@ -14,31 +14,37 @@ import (
"go.uber.org/zap"
)
type CtxKey string
func (x CtxKey) String() string {
return string(x)
}
const (
GinContextKey = "ginContext"
HeaderXTimestampKey = "Timestamp"
KeyReqBody = "reqBody"
KeyRspBody = "rspBody"
KeyRspCode = "rspCode"
KeyOApiReqBody = "oApiReqBody%s"
KeyOApiRspBody = "oApiRspBody%s"
KeyAppName = "appName"
KeyApiStartTime = "apiStartTime"
KeyClientIP = "clientIP"
KeyUID = "userId"
KeyUType = "userType"
KeyCompanyID = "companyId"
KeyShopID = "shopID"
KeyUName = "uname"
KeyToken = "token"
KeyCost = "X-Request-Cost"
GinContextKey CtxKey = "ginContext"
HeaderXTimestampKey CtxKey = "Timestamp"
KeyReqBody CtxKey = "reqBody"
KeyRspBody CtxKey = "rspBody"
KeyRspCode CtxKey = "rspCode"
KeyOApiReqBody CtxKey = "oApiReqBody%s"
KeyOApiRspBody CtxKey = "oApiRspBody%s"
KeyAppName CtxKey = "appName"
KeyApiStartTime CtxKey = "apiStartTime"
KeyClientIP CtxKey = "clientIP"
KeyUID CtxKey = "userId"
KeyUType CtxKey = "userType"
KeyCompanyID CtxKey = "companyId"
KeyShopID CtxKey = "shopID"
KeyUName CtxKey = "uname"
KeyToken CtxKey = "token"
KeyCost CtxKey = "X-Request-Cost"
)
var (
HeaderXRequestIDKey = "X-Request-ID"
ContextTraceIDKey = "X-Request-ID"
HeaderXRequestIDKey CtxKey = "X-Request-ID"
ContextTraceIDKey CtxKey = "X-Request-ID"
)
var (
......@@ -47,7 +53,7 @@ var (
// GetGinCtxTraceID get request id from gin.Context
func GetGinCtxTraceID(c *gin.Context) string {
if v, isExist := c.Get(ContextTraceIDKey); isExist {
if v, isExist := c.Get(ContextTraceIDKey.String()); isExist {
if requestID, ok := v.(string); ok {
return requestID
}
......@@ -57,7 +63,7 @@ func GetGinCtxTraceID(c *gin.Context) string {
// GinTraceIDField get request id field from gin.Context
func GinTraceIDField(c *gin.Context) zap.Field {
return zap.String(ContextTraceIDKey, GetGinCtxTraceID(c))
return zap.String(ContextTraceIDKey.String(), GetGinCtxTraceID(c))
}
// CtxRequestID get request id from context.Context
......@@ -87,23 +93,23 @@ func CtxGetGinCtx(c context.Context) *gin.Context {
// CtxTraceIDField get request id field from context.Context
func CtxTraceIDField(c context.Context) zap.Field {
return zap.String(ContextTraceIDKey, CtxRequestID(c))
return zap.String(ContextTraceIDKey.String(), CtxRequestID(c))
}
func GetGinUserID(c *gin.Context) xsf.ID {
return getGinVal[xsf.ID](c, KeyUID)
return getGinVal[xsf.ID](c, KeyUID.String())
}
func GetGinShopID(c *gin.Context) xsf.ID {
return getGinVal[xsf.ID](c, KeyShopID)
return getGinVal[xsf.ID](c, KeyShopID.String())
}
func GetCtxUserID(c context.Context) xsf.ID {
return getCtxVal[xsf.ID](c, KeyUID)
return getCtxVal[xsf.ID](c, KeyUID.String())
}
func GetCtxShopID(c context.Context) xsf.ID {
return getCtxVal[xsf.ID](c, KeyShopID)
return getCtxVal[xsf.ID](c, KeyShopID.String())
}
func GetCtxString(c context.Context, key string) string {
val := c.Value(key)
......@@ -122,10 +128,10 @@ func GetCtxUserToken(c context.Context) string {
}
func GetGinCtxTid(c *gin.Context) string {
tid := c.GetString(ContextTraceIDKey)
tid := c.GetString(ContextTraceIDKey.String())
if tid == "" {
tid = GenerateTid()
c.Set(ContextTraceIDKey, tid)
c.Set(ContextTraceIDKey.String(), tid)
}
return tid
}
......@@ -161,7 +167,7 @@ func GetClientIP(ctx context.Context) string {
}
func WrapCtx(c *gin.Context) context.Context {
ctx := context.WithValue(c.Request.Context(), ContextTraceIDKey, c.GetString(ContextTraceIDKey)) //nolint
ctx := context.WithValue(c.Request.Context(), ContextTraceIDKey, c.GetString(ContextTraceIDKey.String())) //nolint
for k, v := range c.Keys {
ctx = context.WithValue(ctx, k, v) //nolint
}
......@@ -184,15 +190,15 @@ func GetGinCtx(ctx context.Context) (*gin.Context, error) {
}
func GetCtxUID(c context.Context) uint {
return getCtxVal[uint](c, KeyUID)
return getCtxVal[uint](c, KeyUID.String())
}
func GetCtxUType(c context.Context) uint {
return getCtxVal[uint](c, KeyUType)
return getCtxVal[uint](c, KeyUType.String())
}
func GetCtxCompanyID(c context.Context) uint {
return getCtxVal[uint](c, KeyCompanyID)
return getCtxVal[uint](c, KeyCompanyID.String())
}
func getGinVal[T any](c *gin.Context, key string) T {
......@@ -218,7 +224,7 @@ func getCtxVal[T any](c context.Context, key string) T {
}
func GetGinReq(c *gin.Context) []byte {
v, ok1 := c.Get(KeyReqBody)
v, ok1 := c.Get(KeyReqBody.String())
if ok1 {
ret, ok2 := v.([]byte)
if ok2 {
......@@ -229,7 +235,7 @@ func GetGinReq(c *gin.Context) []byte {
}
func GetGinRsp(c *gin.Context) []byte {
v, ok1 := c.Get(KeyRspBody)
v, ok1 := c.Get(KeyRspBody.String())
if ok1 {
ret, ok2 := v.([]byte)
if ok2 {
......@@ -247,14 +253,14 @@ func SetVal(ctx context.Context, key string, val interface{}) context.Context {
}
func AddApiCost(c *gin.Context, appName string, start time.Time) {
cost := c.Writer.Header().Get(KeyCost)
cost := c.Writer.Header().Get(KeyCost.String())
currentCost := fmt.Sprintf("%s:%s", appName, formatDuration(time.Since(start)))
if cost == "" {
cost = currentCost
} else {
cost = fmt.Sprintf("%s,%s", currentCost, cost)
}
c.Writer.Header().Set(KeyCost, cost)
c.Writer.Header().Set(KeyCost.String(), cost)
}
func formatDuration(d time.Duration) string {
......@@ -266,12 +272,12 @@ func SetApiCost(ctx context.Context, header map[string][]string) {
if ginCtx, _ := GetGinCtx(ctx); ginCtx != nil && len(header) > 0 {
cost := ""
for k, v := range header {
if k == KeyCost {
if k == KeyCost.String() {
cost = strings.Join(v, ",")
}
}
if cost != "" {
ginCtx.Writer.Header().Set(KeyCost, cost)
ginCtx.Writer.Header().Set(KeyCost.String(), cost)
}
}
}
......@@ -102,8 +102,8 @@ func Auth(opts ...JwtOption) gin.HandlerFunc {
}
} else {
xsfID, _ := xsf.ParseString(claims.UID)
c.Set(ctxUtils.KeyUID, xsfID)
c.Set(ctxUtils.KeyUName, claims.Name)
c.Set(ctxUtils.KeyUID.String(), xsfID)
c.Set(ctxUtils.KeyUName.String(), claims.Name)
}
c.Next()
......
......@@ -192,19 +192,19 @@ func Logging(opts ...Option) gin.HandlerFunc {
entity.SetCopyReq(c, buf)
c.Set(ctxUtils.KeyAppName, o.appName)
c.Set(ctxUtils.KeyAppName.String(), o.appName)
reqID := ""
if o.traceIDFrom == 1 {
if v, isExist := c.Get(ctxUtils.ContextTraceIDKey); isExist {
if v, isExist := c.Get(ctxUtils.ContextTraceIDKey.String()); isExist {
if requestID, ok := v.(string); ok {
reqID = requestID
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey, reqID))
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID))
}
}
} else if o.traceIDFrom == 2 {
reqID = c.Request.Header.Get(ctxUtils.HeaderXRequestIDKey)
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey, reqID))
reqID = c.Request.Header.Get(ctxUtils.HeaderXRequestIDKey.String())
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID))
}
o.log.Info("<<<<<<<<<req", fields...)
......@@ -215,7 +215,7 @@ func Logging(opts ...Option) gin.HandlerFunc {
c.Writer = newWriter
ip := ips.GetClientIP(c)
c.Set(ctxUtils.KeyClientIP, ip)
c.Set(ctxUtils.KeyClientIP.String(), ip)
// processing requests
c.Next()
......@@ -232,7 +232,7 @@ func Logging(opts ...Option) gin.HandlerFunc {
zap.ByteString("body", getResponseBody(newWriter.body, o.maxLength)),
}
if reqID != "" {
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey, reqID))
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID))
}
o.log.Info(">>>>>>>>>rsp", fields...)
......@@ -256,13 +256,13 @@ func SimpleLog(opts ...Option) gin.HandlerFunc {
reqID := ""
if o.traceIDFrom == 1 {
if v, isExist := c.Get(ctxUtils.ContextTraceIDKey); isExist {
if v, isExist := c.Get(ctxUtils.ContextTraceIDKey.String()); isExist {
if requestID, ok := v.(string); ok {
reqID = requestID
}
}
} else if o.traceIDFrom == 2 {
reqID = c.Request.Header.Get(ctxUtils.HeaderXRequestIDKey)
reqID = c.Request.Header.Get(ctxUtils.HeaderXRequestIDKey.String())
}
// processing requests
......@@ -277,7 +277,7 @@ func SimpleLog(opts ...Option) gin.HandlerFunc {
zap.Int("size", c.Writer.Size()),
}
if reqID != "" {
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey, reqID))
fields = append(fields, zap.String(ctxUtils.ContextTraceIDKey.String(), reqID))
}
o.log.Info("Gin msg", fields...)
}
......
......@@ -20,8 +20,8 @@ type requestIDOptions struct {
func defaultRequestIDOptions() *requestIDOptions {
return &requestIDOptions{
contextRequestIDKey: ctxUtil.ContextTraceIDKey,
headerXRequestIDKey: ctxUtil.HeaderXRequestIDKey,
contextRequestIDKey: ctxUtil.ContextTraceIDKey.String(),
headerXRequestIDKey: ctxUtil.HeaderXRequestIDKey.String(),
}
}
......@@ -32,11 +32,11 @@ func (o *requestIDOptions) apply(opts ...RequestIDOption) {
}
func (o *requestIDOptions) setRequestIDKey() {
if o.contextRequestIDKey != ctxUtil.ContextTraceIDKey {
ctxUtil.ContextTraceIDKey = o.contextRequestIDKey
if o.contextRequestIDKey != ctxUtil.ContextTraceIDKey.String() {
ctxUtil.ContextTraceIDKey = ctxUtil.CtxKey(o.contextRequestIDKey)
}
if o.headerXRequestIDKey != ctxUtil.HeaderXRequestIDKey {
ctxUtil.HeaderXRequestIDKey = o.headerXRequestIDKey
if o.headerXRequestIDKey != ctxUtil.HeaderXRequestIDKey.String() {
ctxUtil.HeaderXRequestIDKey = ctxUtil.CtxKey(o.headerXRequestIDKey)
}
}
......@@ -76,21 +76,21 @@ func RequestID(opts ...RequestIDOption) gin.HandlerFunc {
o.setRequestIDKey()
return func(c *gin.Context) {
requestID := c.Request.Header.Get(ctxUtil.HeaderXRequestIDKey)
requestID := c.Request.Header.Get(ctxUtil.HeaderXRequestIDKey.String())
// Create request id
if requestID == "" {
requestID = ctxUtil.GenerateTid()
c.Request.Header.Set(ctxUtil.HeaderXRequestIDKey, requestID)
c.Request.Header.Set(ctxUtil.HeaderXRequestIDKey.String(), requestID)
}
st := time.Now()
// Expose it for use in the application
c.Set(ctxUtil.ContextTraceIDKey, requestID)
c.Set(ctxUtil.KeyApiStartTime, st)
c.Set(ctxUtil.ContextTraceIDKey.String(), requestID)
c.Set(ctxUtil.KeyApiStartTime.String(), st)
// Set X-Request-Id header
c.Writer.Header().Set(ctxUtil.HeaderXRequestIDKey, requestID)
c.Writer.Header().Set(ctxUtil.HeaderXRequestIDKey.String(), requestID)
c.Next()
}
......@@ -98,12 +98,12 @@ func RequestID(opts ...RequestIDOption) gin.HandlerFunc {
// HeaderRequestID get request id from the header
func HeaderRequestID(c *gin.Context) string {
return c.Request.Header.Get(ctxUtil.HeaderXRequestIDKey)
return c.Request.Header.Get(ctxUtil.HeaderXRequestIDKey.String())
}
// HeaderRequestIDField get request id field from header
func HeaderRequestIDField(c *gin.Context) zap.Field {
return zap.String(ctxUtil.HeaderXRequestIDKey, HeaderRequestID(c))
return zap.String(ctxUtil.HeaderXRequestIDKey.String(), HeaderRequestID(c))
}
// -------------------------------------------------------------------------------------------
......@@ -113,7 +113,7 @@ var RequestHeaderKey = "request_header_key"
// WrapCtx wrap context, put the Keys and Header of gin.Context into context
func WrapCtx(c *gin.Context) context.Context {
ctx := context.WithValue(c.Request.Context(), ctxUtil.ContextTraceIDKey, c.GetString(ctxUtil.ContextTraceIDKey)) //nolint
ctx := context.WithValue(c.Request.Context(), ctxUtil.ContextTraceIDKey, c.GetString(ctxUtil.ContextTraceIDKey.String())) //nolint
for k, v := range c.Keys {
ctx = context.WithValue(ctx, k, v) //nolint
}
......@@ -122,7 +122,7 @@ func WrapCtx(c *gin.Context) context.Context {
}
func WrapAsyncCtx(c *gin.Context) context.Context {
ctx := context.WithValue(context.Background(), ctxUtil.ContextTraceIDKey, c.GetString(ctxUtil.ContextTraceIDKey)) //nolint
ctx := context.WithValue(context.Background(), ctxUtil.ContextTraceIDKey, c.GetString(ctxUtil.ContextTraceIDKey.String())) //nolint
for k, v := range c.Keys {
ctx = context.WithValue(ctx, k, v) //nolint
}
......
......@@ -143,9 +143,9 @@ func Out(c *gin.Context, err *errcode.Error, data ...interface{}) {
// status code flat 200, custom error codes in data.code
func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{}) {
c.Writer.Header().Set(ctxUtils.HeaderXTimestampKey, strconv.FormatInt(time.Now().Unix(), 10))
appName := c.GetString(ctxUtils.KeyAppName)
stTime := c.GetTime(ctxUtils.KeyApiStartTime)
c.Writer.Header().Set(ctxUtils.HeaderXTimestampKey.String(), strconv.FormatInt(time.Now().Unix(), 10))
appName := c.GetString(ctxUtils.KeyAppName.String())
stTime := c.GetTime(ctxUtils.KeyApiStartTime.String())
ctxUtils.AddApiCost(c, appName, stTime)
if len(data) > 0 {
......@@ -158,13 +158,13 @@ func respJSONWith200(c *gin.Context, code int, msg string, data ...interface{})
// Success return success
func Success(c *gin.Context, data ...interface{}) {
c.Set(ctxUtils.KeyRspCode, 1)
c.Set(ctxUtils.KeyRspCode.String(), 1)
respJSONWith200(c, errcode.Success.Code(), errcode.Success.Msg(), data...)
}
// SuccessWithPage return success
func SuccessWithPage[T any](c *gin.Context, list []*T, total int64) {
c.Set(ctxUtils.KeyRspCode, 1)
c.Set(ctxUtils.KeyRspCode.String(), 1)
if list == nil {
list = []*T{}
}
......@@ -173,7 +173,7 @@ func SuccessWithPage[T any](c *gin.Context, list []*T, total int64) {
// SuccessWithList return success
func SuccessWithList[T any](c *gin.Context, list []*T) {
c.Set(ctxUtils.KeyRspCode, 1)
c.Set(ctxUtils.KeyRspCode.String(), 1)
if list == nil {
list = []*T{}
}
......@@ -182,12 +182,12 @@ func SuccessWithList[T any](c *gin.Context, list []*T) {
// ErrorE return error
func ErrorE(c *gin.Context, err *errcode.Error, data ...interface{}) {
c.Set(ctxUtils.KeyRspCode, 0)
c.Set(ctxUtils.KeyRspCode.String(), 0)
respJSONWith200(c, err.Code(), err.Msg(), data...)
}
func Error(c *gin.Context, err error) {
c.Set(ctxUtils.KeyRspCode, 0)
c.Set(ctxUtils.KeyRspCode.String(), 0)
msg := ""
if err != nil {
msg = err.Error()
......
......@@ -25,11 +25,11 @@ func SetCopyReq(c *gin.Context, buf *bytes.Buffer) {
copyHttpReq.URL = c.Request.URL.String()
copyHttpReq.Headers = c.Request.Header
copyHttpReq.Body = buf.String()
c.Set(ctxUtils.KeyReqBody, copyHttpReq)
c.Set(ctxUtils.KeyReqBody.String(), copyHttpReq)
}
func GetCopyReq(c *gin.Context) *CopyHttpReq {
if val, isExist := c.Get(ctxUtils.KeyReqBody); isExist {
if val, isExist := c.Get(ctxUtils.KeyReqBody.String()); isExist {
if req, ok := val.(*CopyHttpReq); ok {
return req
}
......@@ -41,11 +41,11 @@ func SetCopyRsp(c *gin.Context, buf *bytes.Buffer) {
copyHttpRsp := &CopyHttpRsp{}
copyHttpRsp.Headers = c.Writer.Header()
copyHttpRsp.Body = buf.String()
c.Set(ctxUtils.KeyRspBody, copyHttpRsp)
c.Set(ctxUtils.KeyRspBody.String(), copyHttpRsp)
}
func GetCopyRsp(c *gin.Context) *CopyHttpRsp {
if val, isExist := c.Get(ctxUtils.KeyRspBody); isExist {
if val, isExist := c.Get(ctxUtils.KeyRspBody.String()); isExist {
if rsp, ok := val.(*CopyHttpRsp); ok {
return rsp
}
......@@ -59,11 +59,11 @@ func SetCopyApiReq(c *gin.Context, buf *bytes.Buffer) {
copyHttpReq.URL = c.Request.URL.String()
copyHttpReq.Headers = c.Request.Header
copyHttpReq.Body = buf.String()
c.Set(fmt.Sprintf(ctxUtils.KeyOApiReqBody, ctxUtils.GetGinCtxTraceID(c)), copyHttpReq)
c.Set(fmt.Sprintf(ctxUtils.KeyOApiReqBody.String(), ctxUtils.GetGinCtxTraceID(c)), copyHttpReq)
}
func GetCopyApiReq(c *gin.Context) *CopyHttpReq {
if val, isExist := c.Get(fmt.Sprintf(ctxUtils.KeyOApiReqBody, ctxUtils.GetGinCtxTraceID(c))); isExist {
if val, isExist := c.Get(fmt.Sprintf(ctxUtils.KeyOApiReqBody.String(), ctxUtils.GetGinCtxTraceID(c))); isExist {
if req, ok := val.(*CopyHttpReq); ok {
return req
}
......@@ -75,11 +75,11 @@ func SetCopyApiRsp(c *gin.Context, buf *bytes.Buffer) {
copyHttpRsp := &CopyHttpRsp{}
copyHttpRsp.Headers = c.Writer.Header()
copyHttpRsp.Body = buf.String()
c.Set(fmt.Sprintf(ctxUtils.KeyOApiRspBody, ctxUtils.GetGinCtxTraceID(c)), copyHttpRsp)
c.Set(fmt.Sprintf(ctxUtils.KeyOApiRspBody.String(), ctxUtils.GetGinCtxTraceID(c)), copyHttpRsp)
}
func GetCopyApiRsp(c *gin.Context) *CopyHttpRsp {
if val, isExist := c.Get(fmt.Sprintf(ctxUtils.KeyOApiRspBody, ctxUtils.GetGinCtxTraceID(c))); isExist {
if val, isExist := c.Get(fmt.Sprintf(ctxUtils.KeyOApiRspBody.String(), ctxUtils.GetGinCtxTraceID(c))); isExist {
if rsp, ok := val.(*CopyHttpRsp); ok {
return rsp
}
......
......@@ -268,7 +268,7 @@ func (x *Request) send(ctx context.Context) {
x.request.Header.Add(k, v)
}
}
x.request.Header.Add(ctxUtils.HeaderXRequestIDKey, ctxUtils.CtxRequestID(ctx))
x.request.Header.Add(ctxUtils.HeaderXRequestIDKey.String(), ctxUtils.CtxRequestID(ctx))
if x.timeout < 1 {
x.timeout = defaultTimeout
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论