You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gotrace_id/context.go

43 lines
1.1 KiB

2 years ago
package gotrace_id
import (
"context"
2 years ago
"fmt"
2 years ago
"github.com/gin-gonic/gin"
"go.dtapp.net/gostring"
)
// CustomTraceIdContext 自定义设置跟踪编号上下文
2 years ago
func CustomTraceIdContext(ctx context.Context) context.Context {
2 months ago
var traceId = gostring.GetUuId()
2 months ago
return context.WithValue(ctx, TraceIdKey, traceId)
2 years ago
}
// SetCustomTraceId 自定义设置跟踪编号上下文
func SetCustomTraceId(ctx context.Context, traceId string) context.Context {
2 months ago
return context.WithValue(ctx, TraceIdKey, traceId)
}
2 years ago
// SetGinTraceIdContext 设置跟踪编号上下文
2 years ago
func SetGinTraceIdContext(ctx context.Context, c *gin.Context) context.Context {
2 months ago
var traceId = GetGinTraceId(c)
2 months ago
return context.WithValue(ctx, TraceIdKey, traceId)
2 years ago
}
// GetTraceIdContext 通过上下文获取跟踪编号
func GetTraceIdContext(ctx context.Context) string {
2 months ago
return CustomGetTraceIdContext(ctx, TraceIdKey)
}
// CustomGetTraceIdContext 通过自定义上下文获取跟踪编号
func CustomGetTraceIdContext(ctx context.Context, key string) string {
traceId := fmt.Sprintf("%s", ctx.Value(key))
2 years ago
if traceId == Nil {
2 years ago
return ""
}
2 years ago
if len(traceId) <= 0 {
2 years ago
return ""
}
2 years ago
return traceId
2 years ago
}