requestid

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2022 License: MIT Imports: 4 Imported by: 0

README

requestid

RequestID middleware for Go forked from ascarter/requestid with custom extensions to pass the request ID with Twirp RequestID adds a UUID as X-Request-ID header if not already set. It also adds it to the http.Request Context. Use requestid.FromContext to get the generated request id.

Example


package main

import (
	"fmt"
	"html"
	"log"
	"net/http"

	"github.com/elblox/requestid"
)

func handler(w http.ResponseWriter, r *http.Request) {
	rid, _ := requestid.FromContext(r.Context())
	log.Println("Running hello handler:", rid)
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func main() {
	h := http.HandlerFunc(handler)
	http.Handle("/", requestid.RequestIDHandler(h))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Documentation

Overview

Example
package main

import (
	"fmt"
	"html"
	"log"
	"net/http"

	"github.com/elblox/requestid"
)

func handler(w http.ResponseWriter, r *http.Request) {
	rid, _ := requestid.FromContext(r.Context())
	log.Println("Running hello handler:", rid)
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func main() {
	h := http.HandlerFunc(handler)
	http.Handle("/", requestid.RequestIDHandler(h))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
Output:

Index

Examples

Constants

View Source
const HeaderName = "X-Request-ID"

Variables

This section is empty.

Functions

func FromContext

func FromContext(ctx context.Context) (string, bool)

FromContext returns the request id from context.

func NewContext

func NewContext(ctx context.Context, rid string) context.Context

NewContext creates a context with request id set as context value as well as twirp request header.

func RequestIDHandler

func RequestIDHandler(h http.Handler) http.Handler

RequestIDHandler sets unique request id. If header `X-Request-ID` is already present in the request, that is considered the request id. Otherwise, generates a new unique ID.

Types

This section is empty.

Jump to

Keyboard shortcuts

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