First commit

This commit is contained in:
Pavel Shevaev 2022-10-26 10:50:30 +03:00
commit 9cbbebe7d6
4 changed files with 68 additions and 0 deletions

9
go.mod Normal file
View File

@ -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
)

2
go.sum Normal file
View File

@ -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=

42
trc.go Normal file
View File

@ -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)
}

15
trc_test.go Normal file
View File

@ -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.")
}
}