commit 9cbbebe7d6d9d042b06db734518209bd0531c407 Author: Pavel Shevaev Date: Wed Oct 26 10:50:30 2022 +0300 First commit diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..82ca48b --- /dev/null +++ b/go.mod @@ -0,0 +1,9 @@ +module git.bit5.ru/backend/trc + +go 1.13 + +require ( + git.bit5.ru/backend/colog v1.0.0 + git.bit5.ru/backend/errors v1.0.0 + github.com/google/uuid v1.3.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..3dfe1c9 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= diff --git a/trc.go b/trc.go new file mode 100644 index 0000000..b878720 --- /dev/null +++ b/trc.go @@ -0,0 +1,42 @@ +package trc + +import ( + "fmt" + "net/http" + + "git.bit5.ru/backend/colog" + "git.bit5.ru/backend/errors" + "github.com/google/uuid" +) + +type TraceId string + +func NewTraceId() TraceId { + return TraceId(uuid.New().String()) +} + +type SpanId string + +func NewSpanId() SpanId { + return SpanId(uuid.New().String()) +} + +//----------------------------------------------------------------------------- + +const TraceIdHeaderName = "trace-id" + +func RequestTraceId(req *http.Request) (TraceId, error) { + traceIdStr := req.Header.Get(TraceIdHeaderName) + if len(traceIdStr) == 0 { + return "", errors.New("Trace id must be specified.") + } + + return TraceId(traceIdStr), nil +} + +//----------------------------------------------------------------------------- + +func NewTraceLogger(logger *colog.CoLog, traceId TraceId) *colog.CoLog { + prefix := fmt.Sprintf("[trace_id:%s]", traceId) + return logger.Clone().AddPrefix(prefix) +} diff --git a/trc_test.go b/trc_test.go new file mode 100644 index 0000000..68be879 --- /dev/null +++ b/trc_test.go @@ -0,0 +1,15 @@ +package trc_test + +import ( + "testing" + + "git.bit5.ru/backend/trc" +) + +func TestNewTraceId(t *testing.T) { + traceId := trc.NewTraceId() + + if len(traceId) == 0 { + t.Error("Empty traceId.") + } +}