requestid

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2022 License: Apache-2.0 Imports: 3 Imported by: 32

README

RequestID (This is a community driven project)

Request ID middleware for Hertz framework, inspired by requestid. This project would not have been possible without the support from the CloudWeGo community and previous work done by the gin community.

  • Adds an identifier to the response using the X-Request-ID header.
  • Passes the X-Request-ID value back to the caller if it's sent in the request headers.

Install

go get github.com/hertz-contrib/requestid

Usage

Example
func main() {
   h := server.Default()

   h.Use(
      // provide your own request id generator here 
      requestid.New(requestid.WithGenerator(func() string {
         return "cloudwego.io"
      })),
      // set custom header for request id
      requestid.WithCustomHeaderStrKey("your-customised-key"),
)

   // Example ping request.
   h.GET("/ping", func(ctx context.Context, c *app.RequestContext) {
      c.JSON(consts.StatusOK, utils.H{"ping": "pong"})
   })

   h.Spin()
}
Getting the request ID

requestid.Get(c) is a helper function to retrieve request id from request headers. It also works with customised header as defined with WithCustomHeaderStrKey. Note that you may get empty string if it's not present in the request.

// Example / request.
h.GET("/ping", func(ctx context.Context, c *app.RequestContext) {
    c.JSON(consts.StatusOK, utils.H{"ping": "pong", "request-id": requestid.Get(c)})
})

License

This project is under the Apache License 2.0. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(c *app.RequestContext) string

Get returns the request identifier

func New

func New(opts ...Option) app.HandlerFunc

New initializes the RequestID middleware.

Types

type Generator

type Generator func() string

type Handler

type Handler func(ctx context.Context, c *app.RequestContext, requestID string)

type HeaderStrKey

type HeaderStrKey string

type Option

type Option func(*config)

Option for request id generator

func WithCustomHeaderStrKey

func WithCustomHeaderStrKey(s HeaderStrKey) Option

WithCustomHeaderStrKey set custom header key for request id

func WithGenerator

func WithGenerator(g Generator) Option

WithGenerator set generator function

func WithHandler

func WithHandler(handler Handler) Option

WithHandler set handler function for request id with context

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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