Fiber: 馃 How can i get response body after Next()

Created on 9 Jul 2020  路  6Comments  路  Source: gofiber/fiber

Example for Gin framework here. How can do this in fiber?

package main

import (
    "bytes"
    "fmt"

    "github.com/gin-gonic/gin"
)

type responseBodyWriter struct {
    gin.ResponseWriter
    body *bytes.Buffer
}

func (r responseBodyWriter) Write(b []byte) (int, error) {
    r.body.Write(b)
    return r.ResponseWriter.Write(b)
}

func logResponseBody(c *gin.Context) {
    w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
    c.Writer = w
    c.Next()
    fmt.Println("Response body: " + w.body.String())
}

func sayHello(c *gin.Context) {
    c.JSON(200, gin.H{
        "hello": "privationel",
    })
}

func main() {
    r := gin.Default()
    r.Use(logResponseBody)
    r.GET("/", sayHello)
    r.Run()
}
馃 Question

All 6 comments

Thanks for opening your first issue here! 馃帀 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Hi @ferdigokdemir, you can still access the Fasthttp core properties if you want to visit the response body.

c.Fasthttp.Response.Body()

Hi @ferdigokdemir, you can still access the Fasthttp core properties if you want to visit the response body.

c.Fasthttp.Response.Body()

Like this?

app.Use(func(c *fiber.Ctx) {
        c.Next()
        print(c.Fasthttp.Response.Body())
    })

Hi @ferdigokdemir, you can still access the Fasthttp core properties if you want to visit the response body.

c.Fasthttp.Response.Body()

Working! thanks a lot.
But i have a another problem. When i activate gzip, body returning byte array :)
I disable it, and i can see json response.
Must i disable gzip? have a another fix for this?

Example byte array response here

Screen Shot 2020-07-09 at 21 24 00

I found a solution :) c.Fasthttp.Response.BodyGunzip() for gzip body.

    app.Use(func(c *fiber.Ctx) {
        c.Next()
        body, err := c.Fasthttp.Response.BodyGunzip()
        if err != nil {
            log.Println(err)
        }
        log.Println(string(body))
    })

Fixed!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

abowloflrf picture abowloflrf  路  4Comments

ahan picture ahan  路  3Comments

mewben picture mewben  路  3Comments

lucasmdomingues picture lucasmdomingues  路  3Comments

bashery picture bashery  路  4Comments