Skip to content

Commit

Permalink
Add GetRespHeader, GetReqHeaders and TagReqHeaders for logger mw (#1678)
Browse files Browse the repository at this point in the history
* Add GetRespHeader & GetReqHeaders methods.

* Add TagReqHeaders for logger middleware.

* Update README.md
  • Loading branch information
efectn committed Dec 31, 2021
1 parent e26ed83 commit 59240b5
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 4 deletions.
24 changes: 24 additions & 0 deletions ctx.go
Expand Up @@ -578,6 +578,30 @@ func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue)
}

// GetReqHeaders returns the HTTP request headers.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *Ctx) GetReqHeaders() map[string]string {
headers := make(map[string]string)
c.Request().Header.VisitAll(func(k, v []byte) {
headers[string(k)] = c.app.getString(v)
})

return headers
}

// GetRespHeaders returns the HTTP response headers.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
func (c *Ctx) GetRespHeaders() map[string]string {
headers := make(map[string]string)
c.Response().Header.VisitAll(func(k, v []byte) {
headers[string(k)] = c.app.getString(v)
})

return headers
}

// Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting instead.
Expand Down
34 changes: 34 additions & 0 deletions ctx_test.go
Expand Up @@ -2752,6 +2752,40 @@ func Test_Ctx_GetRespHeader(t *testing.T) {
utils.AssertEqual(t, c.GetRespHeader(HeaderContentType), "application/json")
}

// go test -run Test_Ctx_GetRespHeaders
func Test_Ctx_GetRespHeaders(t *testing.T) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)

c.Set("test", "Hello, World 👋!")
c.Set("foo", "bar")
c.Response().Header.Set(HeaderContentType, "application/json")

utils.AssertEqual(t, c.GetRespHeaders(), map[string]string{
"Content-Type": "application/json",
"Foo": "bar",
"Test": "Hello, World 👋!",
})
}

// go test -run Test_Ctx_GetReqHeaders
func Test_Ctx_GetReqHeaders(t *testing.T) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)

c.Request().Header.Set("test", "Hello, World 👋!")
c.Request().Header.Set("foo", "bar")
c.Request().Header.Set(HeaderContentType, "application/json")

utils.AssertEqual(t, c.GetReqHeaders(), map[string]string{
"Content-Type": "application/json",
"Foo": "bar",
"Test": "Hello, World 👋!",
})
}

// go test -run Test_Ctx_IsFromLocal
func Test_Ctx_IsFromLocal(t *testing.T) {
t.Parallel()
Expand Down
5 changes: 3 additions & 2 deletions middleware/logger/README.md
Expand Up @@ -143,8 +143,9 @@ const (
TagLatency = "latency"
TagStatus = "status" // response status
TagResBody = "resBody" // response body
TagQueryStringParams = "queryParams" // request query parameters
TagBody = "body" // request body
TagReqHeaders = "reqHeaders"
TagQueryStringParams = "queryParams" // request query parameters
TagBody = "body" // request body
TagBytesSent = "bytesSent"
TagBytesReceived = "bytesReceived"
TagRoute = "route"
Expand Down
7 changes: 7 additions & 0 deletions middleware/logger/logger.go
Expand Up @@ -35,6 +35,7 @@ const (
TagLatency = "latency"
TagStatus = "status"
TagResBody = "resBody"
TagReqHeaders = "reqHeaders"
TagQueryStringParams = "queryParams"
TagBody = "body"
TagBytesSent = "bytesSent"
Expand Down Expand Up @@ -244,6 +245,12 @@ func New(config ...Config) fiber.Handler {
return appendInt(buf, c.Response().StatusCode())
case TagResBody:
return buf.Write(c.Response().Body())
case TagReqHeaders:
reqHeaders := make([]string, 0)
for k, v := range c.GetReqHeaders() {
reqHeaders = append(reqHeaders, k+"="+v)
}
return buf.Write([]byte(strings.Join(reqHeaders, "&")))
case TagQueryStringParams:
return buf.WriteString(c.Request().URI().QueryArgs().String())
case TagMethod:
Expand Down
4 changes: 2 additions & 2 deletions middleware/logger/logger_test.go
Expand Up @@ -140,15 +140,15 @@ func Test_Logger_All(t *testing.T) {

app := fiber.New()
app.Use(New(Config{
Format: "${pid}${referer}${protocol}${ip}${ips}${host}${url}${ua}${body}${route}${black}${red}${green}${yellow}${blue}${magenta}${cyan}${white}${reset}${error}${header:test}${query:test}${form:test}${cookie:test}${non}",
Format: "${pid}${reqHeaders}${referer}${protocol}${ip}${ips}${host}${url}${ua}${body}${route}${black}${red}${green}${yellow}${blue}${magenta}${cyan}${white}${reset}${error}${header:test}${query:test}${form:test}${cookie:test}${non}",
Output: buf,
}))

resp, err := app.Test(httptest.NewRequest("GET", "/?foo=bar", nil))
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, fiber.StatusNotFound, resp.StatusCode)

expected := fmt.Sprintf("%dhttp0.0.0.0example.com/?foo=bar/%s%s%s%s%s%s%s%s%s-", os.Getpid(), cBlack, cRed, cGreen, cYellow, cBlue, cMagenta, cCyan, cWhite, cReset)
expected := fmt.Sprintf("%dHost=example.comhttp0.0.0.0example.com/?foo=bar/%s%s%s%s%s%s%s%s%s-", os.Getpid(), cBlack, cRed, cGreen, cYellow, cBlue, cMagenta, cCyan, cWhite, cReset)
utils.AssertEqual(t, expected, buf.String())
}

Expand Down

0 comments on commit 59240b5

Please sign in to comment.