requestid

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2020 License: Apache-2.0 Imports: 4 Imported by: 0

README

requestid

Description

this repository is a collection of middlewares, used to get a requestID from an http request, and set it in rest clients used to perform requests.

supported frameworks

Framework Support Version
Resty v2
Echo v4
Atreugo v10

how to install

go get github.com/Wr4thon/requestid@v0.2.0

How to use

resty
package main

import (
	"context"

	"github.com/Wr4thon/requestid"
	"github.com/go-resty/resty/v2"
)

func main(){
	client := resty.
		New().
		OnBeforeRequest(requestid.RestyMiddleware)

	// this most likely will be set by an http framework such as atreugo or echo.
	ctx := context.TODO()
	ctx = requestid.Set(ctx, "<TheRequestID>")

	resp, err := client.R().
		SetContext(ctx).
		Get("https://example.com")

	if err != nil {
		panic(err)
	}

	println(string(resp.Body()))
}

echo
package main

import (
	"net/http"

	"github.com/Wr4thon/requestid"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	e := echo.New()
	e.Use(middleware.RequestID())
	e.Use(requestid.EchoMiddleware())

	e.GET("/", func(c echo.Context) error {
		rid, err := requestid.Get(c.Request().Context())

		if err != nil {
      println(err.Error())
			return c.NoContent(http.StatusInternalServerError)
		}

		println(rid)
		return c.NoContent(http.StatusNoContent)
	})

	e.Logger.Error(e.Start(":1337"))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrNotFound is the error when the context does not contain a reqestID.
	ErrNotFound = errors.New("context does not contain a requestID")
	// ErrWrongType is the error when the value in the context has the wrong type.
	ErrWrongType = errors.New("value is not of type string")
)

Functions

func Copy added in v0.4.0

func Copy(source context.Context, target *context.Context) error

Copy gets the requestID from the source context, and copies it over to the target context.

func EchoMiddleware

func EchoMiddleware() echo.MiddlewareFunc

EchoMiddleware puts the requestID into the context value.

func Get

func Get(ctx context.Context) (requestID string, err error)

Get returns the stored value of the requestIDKey if no value is present (ErrNotFound) or for some reason the value is not a string (ErrWrongType) an error is returned.

func RestyMiddleware

func RestyMiddleware(c *resty.Client, r *resty.Request) error

RestyMiddleware gets the requestID from the context and puts it into the header.

func Set

func Set(ctx context.Context, requestID string) context.Context

Set sets the requestID to the context.

Types

This section is empty.

Jump to

Keyboard shortcuts

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