Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Ravil Zaripov committed Sep 5, 2024
0 parents commit 9e71cd5
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/rzaripov1990/trace_ctx

go 1.22.2

require github.com/google/uuid v1.6.0
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
59 changes: 59 additions & 0 deletions trace_ctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Package `trace_ctx` enables precise control over the
// setting and retrieval of the `trace_id` within a context,
// ensuring that the unique identifier is consistently managed
// throughout the lifecycle of a request.
//
// This capability is essential for maintaining traceability
// and correlating log entries across different components
// of the application.

package trace_ctx

import (
"context"
"strings"

"github.com/google/uuid"
)

var (
TraceKeyInCtx any = new(byte)
rp = strings.NewReplacer("-", "")
)

const (
TraceIDKeyName = "trace_id"
)

func genTraceID() string {
return rp.Replace(uuid.NewString())
}

func GetTraceID(ctx context.Context) string {
if ctx == nil {
return genTraceID()
}

val := ctx.Value(TraceKeyInCtx)
if val != nil {
return val.(string)
}

return genTraceID()
}

func WithTraceID(ctx context.Context) context.Context {
if ctx == nil {
panic("ctx is nil")
}

return context.WithValue(ctx, TraceKeyInCtx, genTraceID())
}

func SetTraceID(ctx context.Context, traceID string) context.Context {
if ctx == nil {
panic("ctx is nil")
}

return context.WithValue(ctx, TraceKeyInCtx, traceID)
}

0 comments on commit 9e71cd5

Please sign in to comment.