trace

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 22, 2026 License: MIT Imports: 8 Imported by: 0

README

Go Trace Package

A simple Go package for propagating trace data through execution contexts. It provides a Trace type with helpers for context integration, HTTP headers, and JSON serialization.

Installation

[!IMPORTANT] This repository was migrated from github.

Please refer to github.com/iolave/go-trace for versions <= v1.0.0

go get codeberg.org/mice1337/go-trace

Usage

Creating a Trace

The Trace type is a map[string]string. The Set method enforces that keys are in snake_case.

package main

import (
	"fmt"
	"codeberg.org/mice1337/go-trace"
)

func main() {
	// Create a new trace
	t := make(trace.Trace)
    // or:
    //  t := trace.Trace{}

	// Set some data
	err := t.Set("request_id", "xyz-123")
	if err != nil {
		panic(err)
	}

	// Set enforces snake_case keys
	err = t.Set("invalidKey", "some-value")
	if err != nil {
		// Error: trace key must be in snake case, (got invalidKey, expected invalid_key)
		fmt.Println("Error:", err)
	}

	fmt.Println(t.Get("request_id")) // xyz-123
}
Context Integration

You can easily set and get a trace from a context.Context.

package main

import (
	"context"
	"fmt"
	"codeberg.org/mice1337/go-trace"
)

func main() {
    ctx := context.Background()

    // Get the trace from the context
	t := trace.GetFromContext(ctx)

    // Add more data to the trace
    t.Set("service_name", "my-service")

	// Set the trace in a context
	ctx = t.SetInContext(context.Background())
    
    // Later in a downstream function
    t = trace.GetFromContext(ctx)
    fmt.Println(t.Get("service_name")) // my-service
}
HTTP Request Integration

The package provides helpers to inject and extract trace data from HTTP headers, prefixed with X-Trace-.

package main

import (
	"fmt"
	"codeberg.org/mice1337/go-trace"
	"net/http"
	"net/http/httptest"
)

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Get trace from incoming request headers
		t, err := trace.GetFromHTTPRequest(r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		fmt.Printf("Trace from request: %v\n", t)

		// Add more data to the trace
		t.Set("service_name", "my-service")

		// Set trace headers for an outgoing response (or a new client request)
		t.SetHTTPHeaders(w.Header())
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, "Hello, client")
	})

	// Simulate an incoming request from an upstream service
	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	req.Header.Set("X-Trace-Request-Id", "xyz-abc-123")
	req.Header.Set("X-Trace-Source", "api-gateway")


	w := httptest.NewRecorder()
	handler(w, req)

	fmt.Printf("Response Headers: %v\n", w.Header())
}
JSON Serialization

The Trace type implements the json.Marshaler interface.

package main

import (
	"encoding/json"
	"fmt"
	"codeberg.org/mice1337/go-trace"
)

func main() {
	t := make(trace.Trace)
	t.Set("request_id", "xyz-123")
	t.Set("user_id", "42")

	jsonData, err := json.Marshal(t)
	if err != nil {
		panic(err)
	}

	// {"request_id":"xyz-123","user_id":"42"}
	fmt.Println(string(jsonData))
}

Documentation

Overview

The trace package provides a Trace struct for storing and retrieving trace data.

It also provides useful functions for setting and retrieving the trace to and from the context.

There's also helpers for setting and retrieving the trace from http requests.

Index

Constants

View Source
const CTX_KEY = "trace"

key used to store and retrieve the trace from a context.

View Source
const (
	ERR_NAME = "trace_error"
)
View Source
const HTTP_HEADER_PREFIX = "X-Trace-"

HTTP_HEADER_PREFIX is the prefix that trace headers must have.

Variables

This section is empty.

Functions

This section is empty.

Types

type Trace

type Trace map[string]string

Trace is a map used to store trace data within an execution context.

i.e. An http request or an async event.

Built-in properties:

A unique identifier for the trace.

func GetFromContext

func GetFromContext(ctx context.Context) Trace

GetFromContext returns the trace from a context using the key trace.CTX_KEY.

If the trace value is nil or is not of type trace.Trace, it will return a new empty trace. Returned trace will always be non-nil.

func GetFromHTTPRequest

func GetFromHTTPRequest(req *http.Request) (trace Trace, err error)

GetFromHTTPRequest builds the trace struct from an http.Request req. It does by finding headers with the trace.HTTP_HEADER_PREFIX then removeing the prefix and converting the key to snake case.

It will return an error if req is nil or if req.Header is nil. trace will always be non-nil.

Errors are of type github.com/iolave/go-errors.GenericError and have the name trace.ERR_NAME. Errors can be casted to this type.

_, err := trace.GetFromHTTPRequest(nil)
if err != nil {
	e := err.(*errors.GenericError)
}

func (Trace) Get

func (t Trace) Get(k string) string

Get returns the value of the given key.

func (Trace) MarshalJSON

func (t Trace) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of the trace.

If the trace is nil, it will return an empty JSON object.

func (Trace) Set

func (t Trace) Set(k string, v string) error

Set sets the value v fot the given key k. Keys must be in snake case, otherwise it will return an error.

Errors are of type github.com/iolave/go-errors.GenericError and have the name trace.ERR_NAME. Errors can be casted to this type.

err := trace.Set("mykey", "this-will-error")
if err != nil {
	e := err.(*errors.GenericError)
}

func (Trace) SetHTTPHeaders

func (t Trace) SetHTTPHeaders(h http.Header)

SetHTTPHeaders sets trace data into the given http.Header h. It does by converting the trace keys underscores to dashes and appending at the beginning of each header key the trace.HTTP_HEADER_PREFIX value.

If h is nil, it will do nothing.

func (Trace) SetInContext

func (t Trace) SetInContext(ctx context.Context) context.Context

SetInContext sets the trace in a context using the key trace.CTX_KEY and returns the a new context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL