Created
February 5, 2021 20:49
-
-
Save graphaelli/ae416585c67f9b50f9f326a50ed26c91 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
cryptorand "crypto/rand" | |
"encoding/binary" | |
"fmt" | |
"log" | |
"math/rand" | |
"time" | |
) | |
type TraceID [16]byte // go.elastic.co/apm/model.TraceID | |
type SpanID [8]byte // go.elastic.co/apm/model.SpanID | |
// https://github.com/elastic/apm-agent-go/blob/dd3e8c593580e7b80a98b57e1cc6e017e56747b4/model/marshal.go#L666-L672 | |
func hex(t []byte) []byte { | |
const hextable = "0123456789abcdef" | |
var buf []byte | |
for _, v := range t { | |
buf = append(buf, hextable[v>>4]) | |
buf = append(buf, hextable[v&0x0f]) | |
} | |
return buf | |
} | |
// go.elastic.co/apm/module/apmhttp.FormatTraceparentHeader | |
func FormatTraceparentHeader(t TraceID, s SpanID) string { | |
var options uint8 | |
return fmt.Sprintf("%02x-%032x-%016x-%02x", 0, t[:], s[:], options) | |
} | |
func main() { | |
rand.Seed(time.Now().Unix()) | |
var transactionID SpanID | |
if _, err := cryptorand.Read(transactionID[:]); err != nil { | |
log.Fatal(err) | |
} | |
var traceID TraceID | |
// https://github.com/elastic/apm-agent-go/blob/dd3e8c593580e7b80a98b57e1cc6e017e56747b4/transaction.go#L91-L92 | |
binary.LittleEndian.PutUint64(traceID[:8], rand.Uint64()) | |
binary.LittleEndian.PutUint64(traceID[8:], rand.Uint64()) | |
fmt.Println("TraceID:", string(hex(traceID[:]))) | |
fmt.Println("SpanID:", string(hex(transactionID[:]))) | |
fmt.Println("Traceparent:", FormatTraceparentHeader(traceID, transactionID)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment