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() {
|
2022-01-14 13:48:41 +01:00
|
|
|
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")
|
2022-01-17 11:28:17 +01:00
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2022-01-14 13:48:41 +01:00
|
|
|
}))
|
|
|
|
|
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) {
|
2022-01-17 11:28:17 +01:00
|
|
|
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()
|
2022-01-14 13:48:41 +01:00
|
|
|
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"))
|
|
|
|
}
|