logginghandler/logginghandler_test.go

46 lines
1022 B
Go
Raw Permalink Normal View History

2020-10-13 15:26:40 +02:00
package logginghandler_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
2021-01-18 11:46:22 +01:00
"github.com/rs/zerolog/log"
2020-10-13 15:26:40 +02:00
"github.com/stretchr/testify/assert"
2021-01-18 11:02:17 +01:00
"go.xsfx.dev/logginghandler"
2020-10-13 15:26:40 +02:00
)
2021-01-18 11:46:22 +01:00
func Example() {
logger := log.With().Logger()
handler := logginghandler.Handler(logger)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger := logginghandler.Logger(r)
logger.Info().Msg("this is a request")
w.WriteHeader(http.StatusOK)
}))
2021-01-18 11:46:22 +01:00
http.Handle("/", handler)
log.Fatal().Msg(http.ListenAndServe(":5000", nil).Error())
}
2020-10-13 15:26:40 +02:00
func testHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
2020-10-13 15:26:40 +02:00
}
func TestUUID(t *testing.T) {
2021-01-18 11:46:22 +01:00
t.Parallel()
2020-10-13 15:26:40 +02:00
assert := assert.New(t)
req, err := http.NewRequestWithContext(context.Background(), "GET", "/test", nil)
assert.NoError(err)
rr := httptest.NewRecorder()
handler := logginghandler.Handler(log.With().Logger())(http.HandlerFunc(testHandler))
2020-10-13 15:26:40 +02:00
handler.ServeHTTP(rr, req)
assert.NotEmpty(rr.Header().Get("X-Request-ID"))
}