Skip to content

akm/go-requestid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-requestid

CI codecov Enabled Linters Go Report Card Documentation license

Overview

github.com/akm/go-requestid is a go module for request ID. The package name is requestid. It works in the following sequence for each request processing:

  1. requestid gets request ID from HTTP request header or generates request ID
  2. requestid create a new context.Context with request ID
  3. When your application logs with slog.Logger by requestid, the request ID is added to a log record as an attribute.

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 Logger

Setup logger

logger := requestid.NewLoger(slog.NewTextHandler(os.Stdout, nil))

And setup slog Handler for requestid.

See example_test.go for more details.

X-Request-ID

X-Request-ID is an unofficial HTTP request/response header. But it is supported by some services, middlewares, frameworks and libraries.

How to use X-Request-ID varies depending on the situation. X-Request-ID header can be trusted if the application runs behind a proxy such as Envoy or nginx that generates that header. X-Request-ID header is unreliable if your application communicates with the client directly or if your proxy does not modify that header. In the latter case, you should consider using X-Client-Request-ID.

ID generators

requestid provides two ID generators which work with the following packages:

  • math/rand/v2
  • crypto/rand

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •