Giter VIP home page Giter VIP logo

go-requestid's Introduction

RequestID

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

A library to propagate Request ID across the context.

Prerequisites

  • Go >= 1.21

Install

go get go.nhat.io/requestid

Usage

HTTP Server

You can use requestid.NewHandler() to wrap your HTTP handler or requestid.HandlerMiddleware() if you use chi router.

HTTP Client

You can use requestid.DefaultTransport or requestid.NewRoundTripper() to wrap your HTTP transport. If your client factory supports middleware, you can use requestid.RoundTripperMiddleware().

OpenTelemetry Propagation

You can use requestid.Propagator to propagate Request ID across the context. See the doc for more details.

Examples

Example 1: HTTP server and client middleware.

package integration_test

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"go.nhat.io/requestid"
)

func TestHTTP(t *testing.T) {
	t.Parallel()

	actual := ""

	// Setup HTTP Client.
	c := &http.Client{
		Transport: requestid.DefaultTransport,
		Timeout:   time.Second,
	}

	// Spin up server 2.
	srv2 := httptest.NewServer(newRouter(func(w http.ResponseWriter, r *http.Request) {
		actual = requestid.FromContext(r.Context())

		w.WriteHeader(http.StatusOK)
	}))

	t.Cleanup(srv2.Close)

	// Spin up server 1.
	srv1 := httptest.NewServer(newRouter(func(w http.ResponseWriter, r *http.Request) {
		nextReq, err := http.NewRequestWithContext(r.Context(), http.MethodGet, srv2.URL, nil)
		require.NoError(t, err)

		resp, err := c.Do(nextReq)
		require.NoError(t, err)

		defer resp.Body.Close()

		w.WriteHeader(http.StatusOK)
	}))

	t.Cleanup(srv1.Close)

	// Make request for testing.
	requestID := uuid.New().String()

	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv1.URL, nil)
	require.NoError(t, err)

	req.Header.Set("x-request-id", requestID)

	resp, err := c.Do(req)
	require.NoError(t, err)

	defer resp.Body.Close()

	// Assertions.
	assert.Equal(t, http.StatusOK, resp.StatusCode)
	assert.Equal(t, requestID, actual)
}

func newRouter(h func(w http.ResponseWriter, r *http.Request)) *chi.Mux {
	r := chi.NewRouter()

	r.Use(requestid.HandlerMiddleware())
	r.Get("/", h)

	return r
}

Example 2: OpenTelemetry propagation.

package integration_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

	"go.nhat.io/requestid"
)

func TestPropagator(t *testing.T) {
	t.Parallel()

	requestID := uuid.New().String()
	actual := ""

	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		actual = requestid.FromContext(r.Context())
	})

	srv := httptest.NewServer(otelhttp.NewHandler(h, "test",
		otelhttp.WithPropagators(requestid.Propagator{})),
	)

	defer srv.Close()

	req, err := http.NewRequest(http.MethodGet, srv.URL, nil)
	require.NoError(t, err)

	req.Header.Set("x-request-id", requestID)

	resp, err := srv.Client().Do(req)
	require.NoError(t, err)
	require.NoError(t, resp.Body.Close())

	assert.Equal(t, requestID, actual)
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

go-requestid's People

Contributors

dependabot[bot] avatar nhatthm avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.