提交 ce9025b4 authored 作者: mooncake9527's avatar mooncake9527

ctxUtils

上级 5c7ce11a
...@@ -11,7 +11,7 @@ import ( ...@@ -11,7 +11,7 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
"gitlab.wanzhuangkj.com/tush/xpkg/encoding" "gitlab.wanzhuangkj.com/tush/xpkg/encoding"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
xslice "gitlab.wanzhuangkj.com/tush/xpkg/utils/xslice" xslice "gitlab.wanzhuangkj.com/tush/xpkg/utils/xslice"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
......
package xctx package ctxUtils
import ( import (
"context" "context"
...@@ -11,18 +11,11 @@ import ( ...@@ -11,18 +11,11 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
var ( const (
GinContextKey = "gin_context" GinContextKey = "gin_context"
ContextTraceIDKey = "X-Request-ID"
KeyConfigFile = "config_file" KeyConfigFile = "config_file"
KeyConfigCenter = "config_center" KeyConfigCenter = "config_center"
// HeaderXRequestIDKey header request id key
HeaderXRequestIDKey = "X-Request-ID"
HeaderXTimestampKey = "Timestamp" HeaderXTimestampKey = "Timestamp"
KeyReqBody = "req-body" KeyReqBody = "req-body"
KeyRspBody = "rsp-body" KeyRspBody = "rsp-body"
KeyTid = "tid" KeyTid = "tid"
...@@ -34,8 +27,11 @@ var ( ...@@ -34,8 +27,11 @@ var (
KeyUName = "uname" KeyUName = "uname"
KeyToken = "token" KeyToken = "token"
KeyUser = "user" KeyUser = "user"
)
//KeyResp = "resp" var (
HeaderXRequestIDKey = "X-Request-ID"
ContextTraceIDKey = "X-Request-ID"
) )
var ( var (
......
...@@ -4,8 +4,8 @@ package middleware ...@@ -4,8 +4,8 @@ package middleware
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.wanzhuangkj.com/tush/xpkg/errcode" "gitlab.wanzhuangkj.com/tush/xpkg/errcode"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/response" "gitlab.wanzhuangkj.com/tush/xpkg/gin/response"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/jwt" "gitlab.wanzhuangkj.com/tush/xpkg/jwt"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf" "gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
...@@ -102,8 +102,8 @@ func Auth(opts ...JwtOption) gin.HandlerFunc { ...@@ -102,8 +102,8 @@ func Auth(opts ...JwtOption) gin.HandlerFunc {
} }
} else { } else {
xsfID, _ := xsf.ParseString(claims.UID) xsfID, _ := xsf.ParseString(claims.UID)
c.Set(xctx.KeyUID, xsfID) c.Set(ctxUtils.KeyUID, xsfID)
c.Set(xctx.KeyUName, claims.Name) c.Set(ctxUtils.KeyUName, claims.Name)
} }
c.Next() c.Next()
......
...@@ -2,11 +2,13 @@ package middleware ...@@ -2,11 +2,13 @@ package middleware
import ( import (
"bytes" "bytes"
"encoding/json"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/uriUtils"
"io" "io"
"net/http" "net/http"
"time" "time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/ips" "gitlab.wanzhuangkj.com/tush/xpkg/ips"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
...@@ -184,6 +186,13 @@ func Logging(opts ...Option) gin.HandlerFunc { ...@@ -184,6 +186,13 @@ func Logging(opts ...Option) gin.HandlerFunc {
} }
c.Set(ctxUtil.KeyReqBody, buf.Bytes()) c.Set(ctxUtil.KeyReqBody, buf.Bytes())
if c.Request.Method == http.MethodGet && buf.Len() == 0 {
paramMap, err := uriUtils.URLValuePairsToMap(c.Request.URL.RawQuery)
if err == nil {
val, _ := json.Marshal(paramMap)
c.Set(ctxUtil.KeyReqBody, val)
}
}
reqID := "" reqID := ""
if o.traceIDFrom == 1 { if o.traceIDFrom == 1 {
......
...@@ -7,8 +7,8 @@ import ( ...@@ -7,8 +7,8 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/response" "gitlab.wanzhuangkj.com/tush/xpkg/gin/response"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx"
"gitlab.wanzhuangkj.com/tush/xpkg/httpcli" "gitlab.wanzhuangkj.com/tush/xpkg/httpcli"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils" "gitlab.wanzhuangkj.com/tush/xpkg/utils"
......
...@@ -3,7 +3,7 @@ package middleware ...@@ -3,7 +3,7 @@ package middleware
import ( import (
"net/http" "net/http"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap" "go.uber.org/zap"
......
...@@ -2,7 +2,7 @@ package middleware ...@@ -2,7 +2,7 @@ package middleware
import ( import (
"context" "context"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"net/http" "net/http"
"strconv" "strconv"
"time" "time"
......
...@@ -6,7 +6,7 @@ import ( ...@@ -6,7 +6,7 @@ import (
"testing" "testing"
"time" "time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/utils" "gitlab.wanzhuangkj.com/tush/xpkg/utils"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
......
...@@ -4,7 +4,7 @@ import ( ...@@ -4,7 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"go.uber.org/zap" "go.uber.org/zap"
"strconv" "strconv"
"sync" "sync"
...@@ -27,13 +27,13 @@ func (d *RedisDatastore) Add(ctx context.Context, key string, start, value int64 ...@@ -27,13 +27,13 @@ func (d *RedisDatastore) Add(ctx context.Context, key string, start, value int64
c, err := d.client.IncrBy(ctx, k, value).Result() c, err := d.client.IncrBy(ctx, k, value).Result()
if err != nil { if err != nil {
if d.logger != nil { if d.logger != nil {
d.logger.Error(fmt.Sprintf("[SlideWindow] add fail,[k:%s add:%d]", k, value), zap.String("err", err.Error()), zap.String("cost", time.Since(startTime).String()), xctx.CtxTraceIDField(ctx)) d.logger.Error(fmt.Sprintf("[SlideWindow] add fail,[k:%s add:%d]", k, value), zap.String("err", err.Error()), zap.String("cost", time.Since(startTime).String()), ctxUtils.CtxTraceIDField(ctx))
} }
return 0, err return 0, err
} }
_, _ = d.client.Expire(ctx, k, d.ttl).Result() _, _ = d.client.Expire(ctx, k, d.ttl).Result()
if d.logger != nil { if d.logger != nil {
d.logger.Info(fmt.Sprintf("[SlideWindow] add success,[k:%s add:%d -> %d]", k, value, c), zap.String("cost", time.Since(startTime).String()), xctx.CtxTraceIDField(ctx)) d.logger.Info(fmt.Sprintf("[SlideWindow] add success,[k:%s add:%d -> %d]", k, value, c), zap.String("cost", time.Since(startTime).String()), ctxUtils.CtxTraceIDField(ctx))
} }
return c, err return c, err
} }
...@@ -47,12 +47,12 @@ func (d *RedisDatastore) Get(ctx context.Context, key string, start int64) (int6 ...@@ -47,12 +47,12 @@ func (d *RedisDatastore) Get(ctx context.Context, key string, start int64) (int6
err = nil err = nil
} }
if d.logger != nil { if d.logger != nil {
d.logger.Error(fmt.Sprintf("[SlideWindow] get fail [k:%s]", k), zap.String("err", err.Error()), zap.String("cost", time.Since(startTime).String()), xctx.CtxTraceIDField(ctx)) d.logger.Error(fmt.Sprintf("[SlideWindow] get fail [k:%s]", k), zap.String("err", err.Error()), zap.String("cost", time.Since(startTime).String()), ctxUtils.CtxTraceIDField(ctx))
} }
return 0, err return 0, err
} }
if d.logger != nil { if d.logger != nil {
d.logger.Info(fmt.Sprintf("[SlideWindow] get success [k:%s v:%s]", k, value), zap.String("cost", time.Since(startTime).String()), xctx.CtxTraceIDField(ctx)) d.logger.Info(fmt.Sprintf("[SlideWindow] get success [k:%s v:%s]", k, value), zap.String("cost", time.Since(startTime).String()), ctxUtils.CtxTraceIDField(ctx))
} }
return strconv.ParseInt(value, 10, 64) return strconv.ParseInt(value, 10, 64)
} }
......
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gitlab.wanzhuangkj.com/tush/xpkg/errcode" "gitlab.wanzhuangkj.com/tush/xpkg/errcode"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtils "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
) )
...@@ -30,7 +30,7 @@ func newResp(c *gin.Context, code int, msg string, data interface{}) *Result { ...@@ -30,7 +30,7 @@ func newResp(c *gin.Context, code int, msg string, data interface{}) *Result {
Code: code, Code: code,
Msg: msg, Msg: msg,
TimeStamp: time.Now().Unix(), TimeStamp: time.Now().Unix(),
TraceID: ctxUtil.GetGinCtxTid(c), TraceID: ctxUtils.GetGinCtxTid(c),
} }
// ensure that the data field is not nil on return, note that it is not nil when resp.data=[]interface {}, it is serialized to null // ensure that the data field is not nil on return, note that it is not nil when resp.data=[]interface {}, it is serialized to null
...@@ -59,7 +59,7 @@ func writeJSON(c *gin.Context, code int, res interface{}) { ...@@ -59,7 +59,7 @@ func writeJSON(c *gin.Context, code int, res interface{}) {
writeContentType(c.Writer, jsonContentType) writeContentType(c.Writer, jsonContentType)
if res != nil { if res != nil {
resBytes, _ := json.Marshal(res) resBytes, _ := json.Marshal(res)
c.Set(ctxUtil.KeyRspBody, resBytes) c.Set(ctxUtils.KeyRspBody, resBytes)
c.Writer.Write(resBytes) c.Writer.Write(resBytes)
} }
//err := json.NewEncoder(c.Writer).Encode(res) //err := json.NewEncoder(c.Writer).Encode(res)
...@@ -181,10 +181,10 @@ func Error(c *gin.Context, err error) { ...@@ -181,10 +181,10 @@ func Error(c *gin.Context, err error) {
msg = err.Error() msg = err.Error()
if xerr, ok := err.(*xerror.Error); ok { if xerr, ok := err.(*xerror.Error); ok {
if !errcode.IsSysDefinedError(xerr.Code()) { if !errcode.IsSysDefinedError(xerr.Code()) {
logger.Error("api failed.", logger.Err(err), ctxUtil.GinTraceIDField(c)) logger.Error("api failed.", logger.Err(err), ctxUtils.GinTraceIDField(c))
} }
} else { } else {
logger.Error("api failed.", logger.Err(err), ctxUtil.GinTraceIDField(c)) logger.Error("api failed.", logger.Err(err), ctxUtils.GinTraceIDField(c))
} }
} }
// 使用respJSONWith200函数返回错误信息。 // 使用respJSONWith200函数返回错误信息。
......
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
"runtime" "runtime"
"time" "time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
......
...@@ -2,7 +2,7 @@ package interceptor ...@@ -2,7 +2,7 @@ package interceptor
import ( import (
"context" "context"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"sync" "sync"
grpc_metadata "github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata" grpc_metadata "github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata"
......
...@@ -13,7 +13,7 @@ import ( ...@@ -13,7 +13,7 @@ import (
"strings" "strings"
"time" "time"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xjson" "gitlab.wanzhuangkj.com/tush/xpkg/utils/xjson"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
...@@ -255,7 +255,7 @@ func (req *Request) push(ctx context.Context) (*Response, error) { ...@@ -255,7 +255,7 @@ func (req *Request) push(ctx context.Context) (*Response, error) {
buf = bytes.NewBufferString(req.body) buf = bytes.NewBufferString(req.body)
} }
logger.Info("httpcli req", logger.String("body", buf.String()), xctx.CtxTraceIDField(ctx)) logger.Info("httpcli req", logger.String("body", buf.String()), ctxUtils.CtxTraceIDField(ctx))
return req.send(ctx, buf, buf) return req.send(ctx, buf, buf)
} }
...@@ -291,14 +291,14 @@ func getRequestBody(buf *bytes.Buffer, maxLen int) []byte { ...@@ -291,14 +291,14 @@ func getRequestBody(buf *bytes.Buffer, maxLen int) []byte {
} }
func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) (*Response, error) { func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) (*Response, error) {
logger.Info("httpcli req", logger.String("url", req.url), xctx.CtxTraceIDField(ctx)) logger.Info("httpcli req", logger.String("url", req.url), ctxUtils.CtxTraceIDField(ctx))
req.request, req.err = http.NewRequest(req.method, req.url, body) req.request, req.err = http.NewRequest(req.method, req.url, body)
if req.err != nil { if req.err != nil {
return nil, req.err return nil, req.err
} }
if buf != nil { if buf != nil {
requestID := xctx.CtxRequestID(ctx) requestID := ctxUtils.CtxRequestID(ctx)
xctx.SetVal(ctx, fmt.Sprintf("oApiReq-%s", requestID), buf.Bytes()) ctxUtils.SetVal(ctx, fmt.Sprintf("oApiReq-%s", requestID), buf.Bytes())
} }
if req.customRequest != nil { if req.customRequest != nil {
req.customRequest(req.request, buf) req.customRequest(req.request, buf)
...@@ -310,7 +310,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -310,7 +310,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
} }
} }
req.request.Header.Add(xctx.HeaderXRequestIDKey, xctx.CtxRequestID(ctx)) req.request.Header.Add(ctxUtils.HeaderXRequestIDKey, ctxUtils.CtxRequestID(ctx))
if req.timeout < 1 { if req.timeout < 1 {
req.timeout = defaultTimeout req.timeout = defaultTimeout
...@@ -327,7 +327,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -327,7 +327,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
err = retry.Retry(func() error { err = retry.Retry(func() error {
response, err := client.Do(req.request) response, err := client.Do(req.request)
if err != nil { if err != nil {
logger.Info("httpcli fail", logger.Any("err", err), xctx.CtxTraceIDField(ctx)) logger.Info("httpcli fail", logger.Any("err", err), ctxUtils.CtxTraceIDField(ctx))
return xerror.Wrap(err, "client do") return xerror.Wrap(err, "client do")
} }
if response != nil { if response != nil {
...@@ -342,8 +342,8 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -342,8 +342,8 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
return xerror.New(err.Error()) return xerror.New(err.Error())
} }
bodyBuf := bytes.NewBuffer(body) bodyBuf := bytes.NewBuffer(body)
xctx.SetVal(ctx, fmt.Sprintf("oApiRsp-%s", xctx.CtxRequestID(ctx)), bodyBuf.Bytes()) ctxUtils.SetVal(ctx, fmt.Sprintf("oApiRsp-%s", ctxUtils.CtxRequestID(ctx)), bodyBuf.Bytes())
logger.Info("httpcli rsp", logger.Any("body", bodyBuf.String()), xctx.CtxTraceIDField(ctx)) logger.Info("httpcli rsp", logger.Any("body", bodyBuf.String()), ctxUtils.CtxTraceIDField(ctx))
if body != nil { if body != nil {
resp.Body = io.NopCloser(bodyBuf) resp.Body = io.NopCloser(bodyBuf)
} }
...@@ -380,8 +380,8 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -380,8 +380,8 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
err = xerror.New(e.Error()) err = xerror.New(e.Error())
} }
bodyBuf := bytes.NewBuffer(body) bodyBuf := bytes.NewBuffer(body)
xctx.SetVal(ctx, fmt.Sprintf("oApiRsp-%s", xctx.CtxRequestID(ctx)), bodyBuf.Bytes()) ctxUtils.SetVal(ctx, fmt.Sprintf("oApiRsp-%s", ctxUtils.CtxRequestID(ctx)), bodyBuf.Bytes())
logger.Info("httpcli rsp", logger.Any("body", bodyBuf.String()), xctx.CtxTraceIDField(ctx)) logger.Info("httpcli rsp", logger.Any("body", bodyBuf.String()), ctxUtils.CtxTraceIDField(ctx))
if body != nil { if body != nil {
resp.Body = io.NopCloser(bodyBuf) resp.Body = io.NopCloser(bodyBuf)
} }
...@@ -389,7 +389,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer) ...@@ -389,7 +389,7 @@ func (req *Request) send(ctx context.Context, body io.Reader, buf *bytes.Buffer)
} }
if err != nil { if err != nil {
logger.Error("httpcli fail", logger.Any("err", err), xctx.CtxTraceIDField(ctx)) logger.Error("httpcli fail", logger.Any("err", err), ctxUtils.CtxTraceIDField(ctx))
} }
req.response = resp req.response = resp
......
package uriUtils
import (
"net/url"
)
func URLValuePairsToMap(query string) (map[string]any, error) {
values, err := url.ParseQuery(query)
if err != nil {
return nil, err
}
data := make(map[string]interface{})
for key, val := range values {
if len(val) == 1 {
data[key] = val[0]
} else {
data[key] = val
}
}
return data, nil
}
...@@ -2,7 +2,7 @@ package wg ...@@ -2,7 +2,7 @@ package wg
import ( import (
"context" "context"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror" "gitlab.wanzhuangkj.com/tush/xpkg/xerrors/xerror"
"sync" "sync"
......
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
"sync" "sync"
"time" "time"
ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/xctx" ctxUtil "gitlab.wanzhuangkj.com/tush/xpkg/gin/ctxUtils"
"gitlab.wanzhuangkj.com/tush/xpkg/jwt" "gitlab.wanzhuangkj.com/tush/xpkg/jwt"
"gitlab.wanzhuangkj.com/tush/xpkg/logger" "gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf" "gitlab.wanzhuangkj.com/tush/xpkg/utils/xsf"
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论