Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LogFormatterParams.Body reading failed #4056

Open
fengshunli opened this issue Sep 15, 2024 · 1 comment
Open

LogFormatterParams.Body reading failed #4056

fengshunli opened this issue Sep 15, 2024 · 1 comment

Comments

@fengshunli
Copy link

fengshunli commented Sep 15, 2024

Using LogFormatterParams.Request.Body to read c fails, using ctx.Request.Body in *gin.Context works fine

QQ_1726416616521

@JimChenWYU
Copy link

JimChenWYU commented Oct 10, 2024

// LoggerWithConfig instance a Logger middleware with config.
func LoggerWithConfig(conf LoggerConfig) HandlerFunc {
	formatter := conf.Formatter
	if formatter == nil {
		formatter = defaultLogFormatter
	}
       
        ...

	return func(c *Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// Process request
		c.Next()
                
                 ...

		fmt.Fprint(out, formatter(param))
	}
}

If you has been read request.Body in your handler, after in logformat middleware will be none.


like this

package main

import (
	"fmt"
	"io"

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

func main() {
	g := gin.Default()
	g.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string {
		rc := io.NopCloser(params.Request.Body)
		b, err := io.ReadAll(rc)
		fmt.Println(string(b), err)   // none, because `/test` has been read `Body`.
		return ""
	}))
	g.POST("test", func(c *gin.Context) {
		b, _ := io.ReadAll(c.Request.Body)
		c.String(200, "body: %s", string(b))
	})
	g.Run(":8080")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants