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
|
package logginghandler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@ -8,16 +10,19 @@ import (
|
|||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// GetUUID gets the requests UUID from a request.
|
||||||
func GetUUID(r *http.Request) string {
|
func GetUUID(r *http.Request) string {
|
||||||
return r.Header.Get("X-Request-ID")
|
return r.Header.Get("X-Request-ID")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Logger returns a logger with the UUID set.
|
||||||
func Logger(r *http.Request) zerolog.Logger {
|
func Logger(r *http.Request) zerolog.Logger {
|
||||||
logger := log.With().Str("uuid", GetUUID(r)).Logger()
|
logger := log.With().Str("uuid", GetUUID(r)).Logger()
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handler is the http middleware handler.
|
||||||
func Handler(next http.Handler) http.Handler {
|
func Handler(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
uuid := uuid.New().String()
|
uuid := uuid.New().String()
|
||||||
|
@ -2,20 +2,27 @@ package logginghandler_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"go.xsfx.dev/logginghandler"
|
"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) {
|
func testHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Print("got request")
|
log.Print("got request")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUUID(t *testing.T) {
|
func TestUUID(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
assert := assert.New(t)
|
assert := assert.New(t)
|
||||||
req, err := http.NewRequestWithContext(context.Background(), "GET", "/test", nil)
|
req, err := http.NewRequestWithContext(context.Background(), "GET", "/test", nil)
|
||||||
assert.NoError(err)
|
assert.NoError(err)
|
||||||
|
Loading…
Reference in New Issue
Block a user