more docs
This commit is contained in:
parent
57438fd3b0
commit
a67e651757
@ -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()
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user