From a67e6517570cb72549a6e112c3e2fcfbd886870a Mon Sep 17 00:00:00 2001 From: Marvin Steadfast Date: Mon, 18 Jan 2021 11:46:22 +0100 Subject: [PATCH] more docs --- logginghandler.go | 5 +++++ logginghandler_test.go | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/logginghandler.go b/logginghandler.go index 0205e63..b878449 100644 --- a/logginghandler.go +++ b/logginghandler.go @@ -1,3 +1,5 @@ +// Package logginghandler is a simple, zerolog based, request logging http middleware. +// It also sets `X-Request-ID` in the request and response headers. package logginghandler import ( @@ -8,16 +10,19 @@ import ( "github.com/rs/zerolog/log" ) +// GetUUID gets the requests UUID from a request. func GetUUID(r *http.Request) string { return r.Header.Get("X-Request-ID") } +// Logger returns a logger with the UUID set. func Logger(r *http.Request) zerolog.Logger { logger := log.With().Str("uuid", GetUUID(r)).Logger() return logger } +// Handler is the http middleware handler. func Handler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { uuid := uuid.New().String() diff --git a/logginghandler_test.go b/logginghandler_test.go index 1b78964..b74a67e 100644 --- a/logginghandler_test.go +++ b/logginghandler_test.go @@ -2,20 +2,27 @@ package logginghandler_test import ( "context" - "log" "net/http" "net/http/httptest" "testing" + "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "go.xsfx.dev/logginghandler" ) +func Example() { + handler := logginghandler.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + http.Handle("/", handler) + log.Fatal().Msg(http.ListenAndServe(":5000", nil).Error()) +} + func testHandler(w http.ResponseWriter, r *http.Request) { log.Print("got request") } func TestUUID(t *testing.T) { + t.Parallel() assert := assert.New(t) req, err := http.NewRequestWithContext(context.Background(), "GET", "/test", nil) assert.NoError(err)