zharp

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 44 Imported by: 0

README

zharp-go-lib

Zharp Application Monitoring for Go: every request traced, logs sent with their trace, panics and errors grouped into issues. A thin layer over the official OpenTelemetry Go SDK — zharp.Init configures the OTLP/HTTP exporters, resource, W3C tracecontext + baggage propagation and a log/slog bridge, and sets the global providers, so any OpenTelemetry instrumentation in your app is sent too.

Full documentation: zharp.io/docs/sdks/go

Install

go get github.com/zharp-io/zharp-go-lib
import zharp "github.com/zharp-io/zharp-go-lib"

Start it

shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Environment: "production"})
defer shutdown(context.Background())

Copy the key from Applications → your app → Setup in Zharp. Leave fields empty to read them from ZHARP_KEY, ZHARP_SERVICE (then OTEL_SERVICE_NAME), ZHARP_ENVIRONMENT, ZHARP_RELEASE, ZHARP_SAMPLE_RATE, ZHARP_TRACING, ZHARP_CAPTURE_BODIES, ZHARP_LOGS, ZHARP_LOG_CORRELATION, ZHARP_CAPTURE_OUTPUT. ZHARP_DISABLED=true turns it off. Init never panics: without a key it prints one line and sends nothing.

Trace requests

net/http

http.ListenAndServe(":8080", zharp.Handler(mux))

Gin — go get github.com/zharp-io/zharp-go-lib/zharpgin

router.Use(zharpgin.Middleware())

Echo (v4) — go get github.com/zharp-io/zharp-go-lib/zharpecho

e.Use(zharpecho.Middleware())

Each request becomes one SERVER span named by its route (GET /orders/{id}), continuing the caller's trace from traceparent. The user and session a Zharp front-end SDK sends in baggage (enduser.id, session.id) go on every span and log of the request. A panic is reported as an unhandled error (and answered with a 500 by zharp.Handler; Gin and Echo keep their own recovery); so is an error a Gin/Echo handler returns that ends in a 5xx.

Outgoing calls: &http.Client{Transport: zharp.Transport(nil)}, with http.NewRequestWithContext. Gin and Echo live in their own modules, so the core module doesn't pull them in.

Secret-looking query values (?token=, key, sig, password, session, …) are recorded as [Filtered] in every span's URL, whatever made the span.

Request and response bodies

Off by default. With CaptureBodies, the spans of incoming requests (zharp.Handler, zharpgin, zharpecho) and of outgoing calls (zharp.Transport) carry what was sent and what came back:

zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api",
	CaptureBodies: &zharp.CaptureBodies{}, // failed requests only; Mode: zharp.BodiesAll for every request
})

or ZHARP_CAPTURE_BODIES=errors (or all) in the environment. More control: &zharp.CaptureBodies{Mode: zharp.BodiesAll, MaxSize: 4096, RedactKeys: []string{"dateOfBirth"}, URLs: []string{"api.example.com"}}.

  • The default keeps bodies only for requests that answered 400 and above (or got no response).
  • Text — JSON, forms, XML, plain text — is kept up to 32 KB (MaxSize, up to 128 KB). Gzip and deflate bodies are inflated first.
  • Every field name is kept. A file upload (multipart/form-data) shows each text field and each file as [file photo.png · image/png · 240 KB]; inline images and long base64 values as [image/png · 24 KB]; a body that isn't text as [binary · application/pdf · 1.2 MB] or [event stream]. File bytes are counted as they pass, never kept.
  • Values under keys that look secret — password, pwd, token, secret, apiKey, authorization, cookie, card, cvv, ssn and similar — become [Filtered] in your process, before anything is sent; under a secret object such as card, each value inside is hidden and its keys kept. Anything else, such as names and email addresses, is sent as it is: add those keys to RedactKeys.
  • Handlers read and write exactly as before; the SDK keeps a copy of the first bytes only.
  • Echo: an error a handler returns is written by Echo after the span ends, so that request's body is captured but its error response isn't — unless echo-otel's OnNextError writes it inside the span (func(c echo.Context, err error) { c.Error(err) }).

Logs

Your app's log lines reach Zharp through the Zharp agent, which reads the app's output (the console, a pod's logs). The SDK doesn't send them too — that would make every line arrive twice. Instead it stamps each line logged during a request with the request's ids, so Zharp links the agent's copy to the request's trace:

time=2026-11-17T08:00:00Z level=INFO msg="Order placed" order_id=42 trace_id=4bf92f3577b34da6a3ce929d0e0e4736 span_id=00f067aa0ba902b7
{"time":"…","level":"INFO","msg":"Order placed","order_id":42,"trace_id":"4bf9…4736","span_id":"00f0…02b7"}

A text line ends with trace_id=<32 hex> span_id=<16 hex>; a JSON line gets trace_id and span_id fields. Lines outside a request, and lines that already have a trace_id, are left as they are. Stamping is on by default; LogCorrelation: zharp.Bool(false) or ZHARP_LOG_CORRELATION=false turns it off.

Where there's no agent (serverless, a job without one), turn logs on and the SDK sends them:

zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Logs: zharp.Bool(true)})

or ZHARP_LOGS=true. Errors, traces and zharp.Log calls are sent either way:

zharp.Log.Info(ctx, "Order placed", "order_id", 42)   // to Zharp only, always; Debug, Info, Warn, Error, Fatal

slog and the log package. After Init, slog.InfoContext(ctx, …) prints as before, stamped (and, with logs on, sent). Use the …Context variants: the stamp comes from the context. The log package goes through slog's default but has no context, so its lines are never stamped. If you set your own default after Init, wrap its handler:

slog.SetDefault(slog.New(zharp.WrapSlogHandler(slog.NewJSONHandler(os.Stdout, nil))))

The stamp is the record's last two attributes. Inside logger.WithGroup(…) a record isn't stamped (its attributes would land in the group). Config.KeepSlogDefault leaves slog.Default alone — neither stamped nor sent; zharp.SlogHandler() gives you Zharp's handler alone.

Plain fmt.Println lines can't be stamped: Go gives no way to know which request a write to os.Stdout belongs to. Log request lines through slog or one of the modules below.

zap, logrus, zerolog — small modules, so the core doesn't pull these libraries in. Each stamps the lines the logger prints and, with logs on, sends each entry its level lets through, with its fields:

// go get github.com/zharp-io/zharp-go-lib/zharpzap
logger := zharpzap.Wrap(zap.Must(zap.NewProduction()))
logger.Info("Order placed", zap.Int("order_id", 42), zharpzap.Context(ctx))   // Context: the request; not printed itself

// go get github.com/zharp-io/zharp-go-lib/zharplogrus
zharplogrus.Install()                                   // the standard logger; or Install(myLogger)
logrus.WithContext(ctx).WithField("order_id", 42).Info("Order placed")

// go get github.com/zharp-io/zharp-go-lib/zharpzerolog
logger := zerolog.New(zharpzerolog.Writer(os.Stdout)).Hook(zharpzerolog.TraceHook{})
logger.Info().Ctx(ctx).Int("order_id", 42).Msg("Order placed")
  • zap: the stamp is the entry's last two fields — the end of a JSON line. zap's development (console) encoder prints fields as a JSON object at the end of the line, which Zharp doesn't read as a stamp: use the JSON encoder where the agent reads the output.
  • logrus: Install wraps the logger's formatter, so call it after SetFormatter; the text and JSON formatters both work. It also has logrus.Fatal send what is queued before it exits.
  • zerolog: TraceHook adds the trace_id and span_id fields (and Writer sends the event in that trace, with logs on). A ConsoleWriter wrapped by Writer ends its line with the stamp.

These work when made before Init. For any other OpenTelemetry log bridge, zharp.LoggerProvider() is a provider that follows the active Init (and sends only with logs on).

Everything printed: CaptureOutput (off by default; only with logs on)

zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Logs: zharp.Bool(true), CaptureOutput: true})

or ZHARP_CAPTURE_OUTPUT=true. Every line written to os.Stdout and os.Stderr — fmt.Println, a log.Logger, a logger with no Zharp module, a library — is sent too, and still prints exactly as before. Its level is read from the line: a JSON record's level/severity (and its message as the body), level=error, ERROR, [warn], zerolog's ERR, klog's E1117 …; otherwise stdout is info and stderr a warning. Colour codes are stripped, an unfinished line is sent after 200 ms, a line is cut at 32 KB, and a line an exact capture above already sent is not sent again. The SDK's own [Zharp] lines are never sent.

It is off by default because Go can't watch a file being written: Init swaps os.Stdout and os.Stderr for pipes, and a goroutine copies each one to the real output before sending its lines. That has costs you should accept knowingly:

  • A line printed right before os.Exit (or log.Fatal) can still be in the pipe when the process ends, and is then lost from the output too. Panics are not affected: the runtime writes them straight to the real stderr.
  • Code that checks whether stdout is a terminal sees a pipe, so it stops printing colours.
  • Only code that reads os.Stdout/os.Stderr after Init is seen: call Init first thing in main, before you build loggers.
  • A printed line has lost its goroutine, so it carries no request — unless it is a JSON record with its own trace_id/span_id. Prefer the exact captures above for request logs.

zharp.Flush and the shutdown function wait for what was printed to come through. After shutdown os.Stdout/os.Stderr are restored; anything still holding the pipe keeps printing.

Logs only

To send logs and errors without tracing:

shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", DisableTracing: true})

or ZHARP_TRACING=false. Logs (zharp.Log; slog and log with Logs on), errors (panics, 5xx handler errors, CaptureError, with the handled flag), SetUser and SetTag work as usual. No spans are created or sent: zharp.Handler, zharpgin and zharpecho make none, zharp.Tracer() spans record nothing (the code inside still runs), and zharp.Transport and the global propagator add no traceparent or baggage to outgoing requests. Incoming traceparent and baggage are still read, so a request's logs and errors carry the caller's trace id, user and session.

Errors

if err := charge(ctx, order); err != nil {
	zharp.CaptureError(ctx, err, "order_id", order.ID)   // handled
}

Go has no global panic hook: defer zharp.Recover() at the top of main and in goroutines reports a panic (fatal), sends it, and panics again.

More

ctx = zharp.SetUser(ctx, zharp.User{ID: account.ID})   // this request's user, when the server knows better
zharp.SetTag("region", "eu-west")                      // on every span and log after
ctx, span := zharp.Tracer().Start(ctx, "render invoice")
defer span.End()
zharp.Flush(ctx)                                       // send now (serverless, end of a job)

Telemetry is batched (5 s), gzip-compressed and retried by the OpenTelemetry exporters.

Development

go test ./... && for m in zharpgin zharpecho zharpzap zharplogrus zharpzerolog; do (cd $m && go test ./...); done
ZHARP_KEY=zpk_… go run ./examples/nethttp

zharpgin, zharpecho, zharpzap, zharplogrus and zharpzerolog are separate modules with a replace to the core in this repo; release them with their own tags (zharpgin/v0.2.0, …) after tagging the core (v0.2.0).

License

MIT © Zharp

Documentation

Overview

Package zharp is Zharp Application Monitoring for Go: a thin layer over the official OpenTelemetry SDK that sends traces, logs and errors to Zharp.

func main() {
	shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api", Environment: "production"})
	defer shutdown(context.Background())

	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", getOrder)
	http.ListenAndServe(":8080", zharp.Handler(mux))
}

Init configures OpenTelemetry — OTLP/HTTP exporters, resource, W3C tracecontext + baggage propagation, and a log/slog bridge — and sets the global providers, so any OpenTelemetry instrumentation in the app is sent too. Handler traces net/http requests; the zharpgin and zharpecho modules do the same for Gin and Echo.

Index

Constants

View Source
const DefaultEndpoint = "https://api.zharp.io/api/v1/otlp"

DefaultEndpoint is where telemetry goes.

View Source
const Version = "0.4.0"

Version is this module's version, sent as telemetry.sdk.version.

Variables

View Source
var Log logger

Log sends logs to Zharp only (not the console), with the trace, user and session of ctx. Arguments after the message are slog-style key-value pairs:

zharp.Log.Info(ctx, "Order placed", "order_id", 42)

It is sent whatever Config.Logs says. slog's default is stamped after Init — slog.InfoContext prints with the request's trace_id and span_id at the end — and, with Config.Logs on, sent too.

Functions

func Bool added in v0.4.0

func Bool(v bool) *bool

Bool returns a pointer to v, for Config.Logs and Config.LogCorrelation.

func CaptureError

func CaptureError(ctx context.Context, err error, args ...any)

CaptureError reports an error you handled. It becomes a Zharp issue (marked handled) with the request's trace, user and session. Extra attributes are slog-style key-value pairs:

if err := charge(ctx, order); err != nil {
	zharp.CaptureError(ctx, err, "order_id", order.ID)
}

func Flush

func Flush(ctx context.Context) error

Flush sends everything queued now — before a serverless function returns, or at the end of a job. It waits until ctx is done at most.

func Handler added in v0.2.0

func Handler(h http.Handler) http.Handler

Handler traces every request to h — one SERVER span each, continuing the caller's trace from its traceparent header, named by the ServeMux pattern ("GET /orders/{id}") — and turns a panic into an unhandled error report and a 500.

http.ListenAndServe(":8080", zharp.Handler(mux))

It is otelhttp.NewHandler with Zharp's panic handling and http.route inside it. With Config.DisableTracing it makes no span: it only reads traceparent and baggage, so the request's logs and errors carry its trace_id, user and session, and still reports panics.

func Init

func Init(cfg Config) func(context.Context) error

Init starts sending to Zharp and returns the function that sends what's left and stops; call it on the way out:

shutdown := zharp.Init(zharp.Config{Key: "zpk_…", Service: "checkout-api"})
defer shutdown(context.Background())

It never panics and never fails the app: without a key, or on a setup error, it writes one line to stderr and returns a shutdown that does nothing. ZHARP_DISABLED=true turns it off.

func LogIDs added in v0.4.0

func LogIDs(ctx context.Context) (traceID, spanID string, ok bool)

LogIDs returns the trace and span ids to stamp on a line logged with ctx: ok is false outside a request, before Init, or with LogCorrelation off. For logging integrations.

func LoggerProvider added in v0.4.0

func LoggerProvider() otellog.LoggerProvider

LoggerProvider returns an OpenTelemetry LoggerProvider that sends to whichever Init is active when a record is emitted, if its Config.Logs is on (nothing before Init or with Logs off) — for logging bridges such as otelzap and otellogrus. Unlike global.GetLoggerProvider, loggers made from it before Init, or before Init is called again, follow the current one. The zharpzap, zharplogrus and zharpzerolog modules use it.

func Recover

func Recover()

Recover reports a panic (unhandled, fatal), waits up to two seconds for it to be sent, then panics again so the program ends as it would have. Defer it first thing in main and in goroutines whose panics you want to see — Go has no global panic hook:

defer zharp.Recover()

func RecoverRequest added in v0.2.0

func RecoverRequest(w http.ResponseWriter, r *http.Request)

RecoverRequest is the panic handling of Handler, for middleware of other routers: deferred inside the request's span, it reports a panic (unhandled), marks the span as failed and answers 500. http.ErrAbortHandler is re-panicked, as net/http expects.

defer zharp.RecoverRequest(w, r)

func ReportPanic added in v0.2.0

func ReportPanic(ctx context.Context, value any)

ReportPanic reports a recovered panic value as an unhandled error, with the stack of the panicking goroutine. Call it in a deferred function, right after recover().

func ReportUnhandledError added in v0.2.0

func ReportUnhandledError(ctx context.Context, err error)

ReportUnhandledError reports an error that ended a request with a 5xx — what a router does with an error a handler returned. For router integrations (zharpgin, zharpecho); in your own code use CaptureError. A returned error carries no stack, so it is grouped by type and message.

func SetTag added in v0.2.0

func SetTag(key, value string)

SetTag puts an attribute on every span and log from now on, across the program. An empty value removes it.

func SetUser added in v0.2.0

func SetUser(ctx context.Context, user User) context.Context

SetUser returns a context whose spans and logs carry this user (enduser.id, enduser.email, enduser.name), and puts it on the span already in ctx. A front end using a Zharp SDK sends its user with each request, so this is for when the server knows better:

ctx := zharp.SetUser(r.Context(), zharp.User{ID: account.ID})
r = r.WithContext(ctx)

func SlogHandler added in v0.2.0

func SlogHandler() slog.Handler

SlogHandler returns a slog.Handler that sends to Zharp, for building your own logger — e.g. to send one logger's records without changing slog's default. Nil before Init.

func StampLine added in v0.4.0

func StampLine(ctx context.Context, line []byte) []byte

StampLine returns a formatted log line ending with " trace_id=… span_id=…" — or, for a JSON record, with "trace_id" and "span_id" fields — when ctx is in a request (see LogIDs). A line that already mentions trace_id, a blank line and the tail of a JSON record are returned as they are; a trailing newline is kept. For logging integrations whose formatter can't add fields.

func Tracer added in v0.2.0

func Tracer() trace.Tracer

Tracer returns a tracer for spans of your own: zharp.Tracer().Start(ctx, "render invoice"). With DisableTracing its spans record nothing (the code inside still runs, and its logs carry the incoming trace_id, if any).

func Transport added in v0.2.0

func Transport(base http.RoundTripper) http.RoundTripper

Transport traces outgoing requests (CLIENT spans) and sends traceparent with them:

client := &http.Client{Transport: zharp.Transport(nil)}

Use the request's context (http.NewRequestWithContext) so the call joins its trace. With Config.DisableTracing requests go straight to base: no span, no traceparent, no baggage.

func WrapSlogHandler added in v0.4.0

func WrapSlogHandler(h slog.Handler) slog.Handler

WrapSlogHandler returns h stamped and sending: each record logged during a request is printed by h with trace_id and span_id as its last attributes (unless LogCorrelation is off or it has a trace_id already), and, with Config.Logs on, sent to Zharp first. For a logger of your own, or a slog.SetDefault made after Init:

slog.SetDefault(slog.New(zharp.WrapSlogHandler(slog.NewJSONHandler(os.Stdout, nil))))

It may be made before Init: it follows whichever Init is active when a record is logged (and does nothing extra before Init). Records keep the trace and span of the context they are logged with (slog.InfoContext). A nil h only sends.

Types

type BodyMode added in v0.3.0

type BodyMode int

BodyMode says which requests have their bodies captured.

const (
	// BodiesErrors captures bodies of failed requests only: status 400 and above, or no response.
	// It is the zero value, so CaptureBodies{} means errors only.
	BodiesErrors BodyMode = iota
	// BodiesAll captures bodies of every request.
	BodiesAll
)

type CaptureBodies added in v0.3.0

type CaptureBodies struct {
	// Mode is BodiesErrors (the default: failed requests only) or BodiesAll.
	Mode BodyMode
	// MaxSize is the number of characters kept per body. Default 32768 (32 KB), at most 131072.
	MaxSize int
	// RedactKeys are more keys whose values are replaced with "[Filtered]", on top of the
	// built-in ones. They match a key ignoring case, '-' and '_' ("accountNumber" also covers
	// account_number).
	RedactKeys []string
	// RedactPatterns are tested against keys as they are; a match is filtered.
	RedactPatterns []*regexp.Regexp
	// URLs limits capture to these requests (incoming and outgoing): a bare host
	// ("api.example.com") matches that host, a string with a scheme matches URLs starting with
	// it. URLPatterns are tested against the full URL. Both empty: every request.
	URLs        []string
	URLPatterns []*regexp.Regexp
}

CaptureBodies puts request and response bodies on HTTP spans — incoming requests (Handler, zharpgin, zharpecho) and outgoing calls (Transport). Set Config.CaptureBodies to turn it on; ZHARP_CAPTURE_BODIES=errors|all does the same without code.

Text is kept up to MaxSize; files in uploads, inline images and binary bodies are described (name, type, size), never sent. Field names are always kept; values under secret-looking keys (password, token, authorization, card, …) are replaced with "[Filtered]" before anything is sent. Other personal data in a body is sent as it is: add its keys to RedactKeys.

type Config

type Config struct {
	// Key is the app's key (zpk_…) from Applications → your app → Setup. Without one, nothing
	// is sent.
	Key string
	// Service is the service.name everything is filed under. Defaults to the last part of the
	// main module's path (github.com/acme/checkout-api → checkout-api).
	Service string
	// Environment, e.g. "production".
	Environment string
	// Release, e.g. "api@2.3.0" — the service.version.
	Release string
	// Endpoint is for Zharp's own testing; leave it empty.
	Endpoint string
	// SampleRate is the share of traces kept, 0 < rate ≤ 1. Zero means 1 (keep all). Logs and
	// errors are always sent.
	SampleRate float64
	// DisableTracing sends logs and errors only ("logs only"): no spans are created or exported,
	// Handler, Transport and the zharpgin/zharpecho middleware trace nothing, and no traceparent or
	// baggage is sent with outgoing requests. An incoming traceparent and baggage are still read,
	// so the logs and errors of a request carry its trace_id, user and session. Logs, errors,
	// SetUser and SetTag work as usual. ZHARP_TRACING=false does the same.
	DisableTracing bool
	// CaptureBodies puts request and response bodies on HTTP spans (Handler, Transport, zharpgin,
	// zharpecho). Nil, the default, is off; ZHARP_CAPTURE_BODIES=errors|all turns it on without
	// code. See CaptureBodies.
	CaptureBodies *CaptureBodies
	// Logs sends what the app logs — slog, the log package, and zap/logrus/zerolog through the
	// zharpzap/zharplogrus/zharpzerolog modules — to Zharp. Nil, the default, is off, unless
	// ZHARP_LOGS=true: where the Zharp agent reads the app's output (a server, a pod) it already
	// brings those lines in, stamped with their request (see LogCorrelation), and sending them too
	// would make every line arrive twice. Turn it on where there is no agent, such as serverless.
	// Errors, traces and zharp.Log calls are sent either way.
	//
	//	Logs: zharp.Bool(true)
	Logs *bool
	// LogCorrelation stamps every line logged during a request with the request's ids: a text line
	// ends with " trace_id=<32 hex> span_id=<16 hex>", a JSON line gets "trace_id" and "span_id"
	// fields. The agent's copy of the line is then linked to its request. It covers slog (and the
	// log package's default logger), WrapSlogHandler and the zharpzap/zharplogrus/zharpzerolog
	// modules; lines printed with fmt can't be stamped. Lines outside a request and lines that
	// already carry a trace_id are left alone. Nil, the default, is on, unless
	// ZHARP_LOG_CORRELATION=false.
	LogCorrelation *bool
	// KeepSlogDefault leaves slog's default logger alone: its lines are neither stamped nor sent.
	// By default Init makes slog.Default (and so the log package) print as before — with the stamp
	// — and, with Logs on, also send to Zharp.
	KeepSlogDefault bool
	// CaptureOutput (only with Logs on) also sends every line printed to os.Stdout and os.Stderr — fmt.Println, a
	// log.Logger or zap/zerolog/logrus logger writing to them, anything — that the exact captures
	// (slog, the log package, zharpzap, zharplogrus, zharpzerolog) didn't already send. Each line
	// still prints exactly as before. Its level is read from the line (a JSON record's level,
	// level=error, ERROR, [warn], klog's E1117…); otherwise stdout is info and stderr a warning. A
	// line an exact capture already sent is not sent again. Off by default:
	// ZHARP_CAPTURE_OUTPUT=true turns it on without code. Init swaps os.Stdout and os.Stderr for
	// pipes, so: call Init first thing in main; a line printed right before os.Exit can be lost;
	// code that checks for a terminal sees a pipe (no colours); and a printed line carries no
	// request unless it is JSON with its own trace_id. See the README.
	CaptureOutput bool

	// SpanExporter and LogExporter replace the OTLP/HTTP exporters to Zharp, and export each span
	// and log synchronously as it ends — for tests (tracetest.NewInMemoryExporter).
	SpanExporter sdktrace.SpanExporter
	LogExporter  sdklog.Exporter
}

Config holds the settings for Init. Anything left empty is read from the environment — ZHARP_KEY, ZHARP_SERVICE (then OTEL_SERVICE_NAME), ZHARP_ENVIRONMENT, ZHARP_RELEASE, ZHARP_SAMPLE_RATE, ZHARP_TRACING, ZHARP_CAPTURE_BODIES, ZHARP_LOGS, ZHARP_LOG_CORRELATION, ZHARP_CAPTURE_OUTPUT — then defaulted.

type RequestBodies added in v0.3.0

type RequestBodies struct {
	// contains filtered or unexported fields
}

RequestBodies records one incoming request's bodies for its span, when Config.CaptureBodies is on. It is for router integrations (zharpgin, zharpecho); Handler uses it already. A nil *RequestBodies (bodies off, or the URL not in CaptureBodies.URLs) does nothing.

func CaptureRequestBodies added in v0.3.0

func CaptureRequestBodies(r *http.Request) *RequestBodies

CaptureRequestBodies starts recording r's bodies. It returns nil when there is nothing to do.

func (*RequestBodies) End added in v0.3.0

func (b *RequestBodies) End(span trace.Span, status int)

End puts the bodies on span, if the status says they are wanted. Call it once, before the span ends.

func (*RequestBodies) Request added in v0.3.0

func (b *RequestBodies) Request(body io.ReadCloser) io.ReadCloser

Request returns the body the handler should read: every byte as before, with a copy of the first ones kept.

func (*RequestBodies) ResponseWriter added in v0.3.0

func (b *RequestBodies) ResponseWriter(w http.ResponseWriter) http.ResponseWriter

ResponseWriter returns w with what is written to it recorded; every interface w implements (Flusher, Hijacker, Pusher, ReaderFrom) is kept.

func (*RequestBodies) Status added in v0.3.0

func (b *RequestBodies) Status() int

Status is the status the response was sent with (200 if the handler set none).

func (*RequestBodies) Wrote added in v0.3.0

func (b *RequestBodies) Wrote(p []byte, header http.Header)

Wrote records response bytes written some other way (a router's own ResponseWriter type). header is the response's header, for its content type.

type User added in v0.2.0

type User struct {
	ID    string
	Email string
	Name  string
}

User is who a request is for.

Directories

Path Synopsis
examples
nethttp command
A net/http server with Zharp.
A net/http server with Zharp.
zharpecho module
zharpgin module
zharpzap module

Jump to

Keyboard shortcuts

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