Skip to content

kataras/requestid

Repository files navigation

Request ID

build status report card godocs

Unique Identifier for each HTTP request. Useful for logging, propagation and e.t.c.

Installation

The only requirement is the Go Programming Language.

$ go get github.com/kataras/requestid

Getting Started

Import the package:

package main

import "github.com/kataras/requestid"

Wrap a handler with the Handler function and retrieve the request ID using the Get function:

import "net/http"

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
        id:= requestid.Get(r)
        w.Write([]byte(id))
    })

    http.ListenAndServe(":8080", requestid.Handler(mux))
}

By-default the requestid middleware uses the X-Request-Id header to extract and set the request ID. It generates a universally unique identifier when the request header is missing. Use custom logic to extract and set the request ID using HandlerWithGenerator:

import "net/http"

func main() {
    // extract from a request header and set to the response header.
    gen := func(w http.ResponseWriter, r *http.Request) string {
        id:= r.Header.Get("X-Custom-Id")
        if id == "" {
            // [custom logic to generate ID...]
        }
        w.Header().Set("X-Custom-Id", id)
        return id
    }

    // [...]
    router := requestid.HandlerWithGenerator(mux, gen)
    http.ListenAndServe(":8080", router)
}

When you want an identifier of request based on the headers, body and e.t.c. use the HashGenerator helper. Note that, the request id will be the same if the same client sends the same requests (that's the goal here):

func main() {
    // [...]

    includeBodyOnHash := false
    gen := requestid.HashGenerator(includeBodyOnHash)

    requestid.HandlerWithGenerator(mux, gen)

    // [...]
}

License

This software is licensed under the MIT License.