From 9cbbebe7d6d9d042b06db734518209bd0531c407 Mon Sep 17 00:00:00 2001 From: Pavel Shevaev Date: Wed, 26 Oct 2022 10:50:30 +0300 Subject: [PATCH] First commit --- go.mod | 9 +++++++++ go.sum | 2 ++ trc.go | 42 ++++++++++++++++++++++++++++++++++++++++++ trc_test.go | 15 +++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 trc.go create mode 100644 trc_test.go 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.") + } +}