logginghandler/logginghandler_test.go

78 lines
1.7 KiB
Go
Raw Normal View History

2020-10-13 15:26:40 +02:00
package logginghandler_test
import (
"bytes"
2020-10-13 15:26:40 +02:00
"context"
"encoding/json"
2020-10-13 15:26:40 +02:00
"net/http"
"net/http/httptest"
"strings"
2020-10-13 15:26:40 +02:00
"testing"
"github.com/rs/zerolog"
2021-01-18 11:46:22 +01:00
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/require"
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.FromRequest(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()
assert := require.New(t)
2020-10-13 15:26:40 +02:00
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"))
}
func TestFromCtx(t *testing.T) {
t.Parallel()
assert := require.New(t)
req, err := http.NewRequestWithContext(context.Background(), "GET", "/test", nil)
assert.NoError(err)
// Create buffer to store output.
var output bytes.Buffer
rr := httptest.NewRecorder()
handler := logginghandler.Handler(zerolog.New(&output))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := logginghandler.FromCtx(r.Context())
log.Info().Msg("hello world")
}))
handler.ServeHTTP(rr, req)
logs := strings.Split(output.String(), "\n")
assert.Len(logs, 3)
var jOut struct{ UUID string }
err = json.Unmarshal([]byte(logs[0]), &jOut)
assert.NoError(err)
assert.NotEmpty(jOut)
}