header.go 866 字节
Newer Older
O
ob-robot 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
package trace

import (
	"context"
	"crypto/rand"
	"fmt"
	"net/http"

	agentlog "github.com/oceanbase/obagent/log"
)

const (
	// trace id
	TraceIdHeader = "X-OCP-Trace-ID"
	// ip
	OcpServerIpHeader = "X-OCP-Server-IP"
)

func GetTraceId(request *http.Request) string {
	// If no traceId passed, generate one.
	traceId := request.Header.Get(TraceIdHeader)
	if traceId == "" {
		traceId = RandomTraceId()
	}
	return traceId
}

func RandomTraceId() string {
	n := 8
	b := make([]byte, n)
	_, err := rand.Read(b)
	if err != nil {
		return ""
	}
	return fmt.Sprintf("%x", b)
}

func ContextWithRandomTraceId() context.Context {
	return context.WithValue(context.Background(), agentlog.TraceIdKey{}, RandomTraceId())
}

func ContextWithTraceId(req *http.Request) context.Context {
	return context.WithValue(context.Background(), agentlog.TraceIdKey{}, GetTraceId(req))
}