Пример #1
0
func TestWithAccessLog(t *testing.T) {
	var buf bytes.Buffer
	defer buf.Reset()

	ctx := ctxlog.NewContext(context.Background(), log.NewStdLogger(log.SetStdWriter(&buf)))

	finalH := ctxhttp.Chain(
		ctxhttp.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			w.WriteHeader(http.StatusTeapot)
			_, err := w.Write([]byte{'1', '2', '3'})
			time.Sleep(time.Millisecond)
			return err
		}),
		ctxhttp.WithAccessLog(),
	)

	r, _ := http.NewRequest("GET", "/gopherine", nil)
	r.RemoteAddr = "127.0.0.1"
	r.Header.Set("User-Agent", "Mozilla")
	r.Header.Set("Referer", "http://rustlang.org")

	w := httptest.NewRecorder()
	if err := finalH.ServeHTTPContext(ctx, w, r); err != nil {
		t.Fatal(err)
	}

	assert.Exactly(t, `123`, w.Body.String())
	assert.Exactly(t, http.StatusTeapot, w.Code)

	want1 := `request error: "" method: "GET" uri: "/gopherine" type: "access" status: "error" status_code: 418 duration:`
	want2 := `size: 3 remote_addr: "127.0.0.1" user_agent: "Mozilla" referer: "http://rustlang.org"`
	assert.Contains(t, buf.String(), want1)
	assert.Contains(t, buf.String(), want2)
}
Пример #2
0
func TestContext(t *testing.T) {
	l := log.NewStdLogger()
	ctx := context.Background()
	ctx = ctxlog.NewContext(ctx, l)

	haveL := ctxlog.FromContext(ctx)
	assert.Exactly(t, l, haveL)

	haveL2 := ctxlog.FromContext(context.TODO())
	assert.Exactly(t, log.BlackHole{}, haveL2)
}