requestid

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2025 License: MIT Imports: 6 Imported by: 0

README

go-requestid

CI codecov license

Install

go get github.com/akm/go-requestid

How to use

import
import "github.com/akm/go-requestid"
Easy way
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Get the request ID by using requestid.Get in your http handler
        requestID := requestid.Get(r.Context())
		w.Write([]byte(fmt.Sprintf("Request ID", requestID)))
		w.WriteHeader(http.StatusOK)
	})

    // Wrap your http handler in order to process requestid
	handlerWithRequestID := requestid.Wrap(handler)
with slog
import "github.com/akm/slogctx"

Setup logger

    slog.SetDefault(slogctx.New(slog.NewTextHandler(os.Stdout, nil)))

you can use slog.NewJSONHandler instead of slog.NewTextHandler.

And setup slog Handler for requestid.

func init() {
	requestid.RegisterSlogHandle("requestid")
}

Then the server log includes requestid.

$ go run ./example
Server started at :8080
time=2024-10-19T23:29:52.650+09:00 level=INFO msg=Start requestid=eVxKgnfE
time=2024-10-19T23:29:52.651+09:00 level=INFO msg=End requestid=eVxKgnfE
time=2024-10-19T23:29:53.389+09:00 level=INFO msg=Start requestid=MJsEk1JG
time=2024-10-19T23:29:53.389+09:00 level=INFO msg=End requestid=MJsEk1JG

See example/main.go for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(ctx context.Context) string

func RandomGenerator

func RandomGenerator(size int) generator

func SetDefaultNamespace added in v0.2.0

func SetDefaultNamespace(ns *Namespace)

func SlogwPrepareFunc added in v0.2.0

func SlogwPrepareFunc(key string) slogctx.HandlePrepareFunc

func Wrap

func Wrap(next http.Handler, opts ...Option) http.Handler

Types

type Namespace added in v0.2.0

type Namespace struct {
	SlogwNamespace *slogctx.Namespace
	// contains filtered or unexported fields
}

func DefaultNamespace added in v0.2.0

func DefaultNamespace() *Namespace

func New added in v0.2.0

func New(opts ...Option) *Namespace

func (*Namespace) Wrap added in v0.2.0

func (f *Namespace) Wrap(h http.Handler) http.Handler

type Option

type Option func(o *Options)

func Generator

func Generator(g generator) Option

func ResponseHeader

func ResponseHeader(h string) Option

func SlogwNamespace added in v0.2.0

func SlogwNamespace(ns *slogctx.Namespace) Option

type Options

type Options struct {
	Generator      generator
	RequestHeader  string
	ResponseHeader string
	SlogwNamespace *slogctx.Namespace
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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