From 70ceaddfae639b5f0eca290382de18f64d5aa62d Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Wed, 18 Oct 2017 15:53:05 +0300 Subject: [PATCH] Added RequestCtx.String that returns unique string representation of the request context --- server.go | 17 ++++++++++++++--- server_test.go | 17 +++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/server.go b/server.go index 90d14e7..28627db 100644 --- a/server.go +++ b/server.go @@ -570,9 +570,7 @@ func (cl *ctxLogger) Printf(format string, args ...interface{}) { ctxLoggerLock.Lock() msg := fmt.Sprintf(format, args...) ctx := cl.ctx - req := &ctx.Request - cl.logger.Printf("%.3f #%016X - %s<->%s - %s %s - %s", - time.Since(ctx.Time()).Seconds(), ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(), req.Header.Method(), ctx.URI().FullURI(), msg) + cl.logger.Printf("%.3f %s - %s", time.Since(ctx.Time()).Seconds(), ctx.String(), msg) ctxLoggerLock.Unlock() } @@ -580,6 +578,13 @@ var zeroTCPAddr = &net.TCPAddr{ IP: net.IPv4zero, } +// String returns unique string representation of the ctx. +// +// The returned value may be useful for logging. +func (ctx *RequestCtx) String() string { + return fmt.Sprintf("#%016X - %s<->%s - %s %s", ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(), ctx.Request.Header.Method(), ctx.URI().FullURI()) +} + // ID returns unique ID of the request. func (ctx *RequestCtx) ID() uint64 { return (ctx.connID << 32) | ctx.connRequestNum @@ -838,6 +843,9 @@ func (ctx *RequestCtx) IsHead() bool { // // Always returns non-nil result. func (ctx *RequestCtx) RemoteAddr() net.Addr { + if ctx.c == nil { + return zeroTCPAddr + } addr := ctx.c.RemoteAddr() if addr == nil { return zeroTCPAddr @@ -849,6 +857,9 @@ func (ctx *RequestCtx) RemoteAddr() net.Addr { // // Always returns non-nil result. func (ctx *RequestCtx) LocalAddr() net.Addr { + if ctx.c == nil { + return zeroTCPAddr + } addr := ctx.c.LocalAddr() if addr == nil { return zeroTCPAddr diff --git a/server_test.go b/server_test.go index 5f12a78..5b3ffa4 100644 --- a/server_test.go +++ b/server_test.go @@ -17,6 +17,23 @@ import ( "github.com/valyala/fasthttp/fasthttputil" ) +func TestRequestCtxString(t *testing.T) { + var ctx RequestCtx + + s := ctx.String() + expectedS := "#0000000000000000 - 0.0.0.0:0<->0.0.0.0:0 - GET http:///" + if s != expectedS { + t.Fatalf("unexpected ctx.String: %q. Expecting %q", s, expectedS) + } + + ctx.Request.SetRequestURI("https://foobar.com/aaa?bb=c") + s = ctx.String() + expectedS = "#0000000000000000 - 0.0.0.0:0<->0.0.0.0:0 - GET https://foobar.com/aaa?bb=c" + if s != expectedS { + t.Fatalf("unexpected ctx.String: %q. Expecting %q", s, expectedS) + } +} + func TestServerErrSmallBuffer(t *testing.T) { logger := &customLogger{} s := &Server{