Bussiere
Bussiere

Reputation: 1154

How to log or print request received with gin?

Example:

func createOrUpdateInfluencer(c *gin.Context) { }

How to print the data in the request received in my function? In my case, I am supposed to receive JSON, how to print it without knowing what it looks like?

Upvotes: 6

Views: 30979

Answers (2)

meshkati
meshkati

Reputation: 2393

by using c.Request you can access to your request object, then print/log everything you must, like the headers:

fmt.Println(g.Request.Header)
fmt.Println(g.Request.Host)
// etc

Upvotes: 1

AnonymousX
AnonymousX

Reputation: 1018

Just read and print the body is ok:

func createOrUpdateInfluencer(c *gin.Context) {
    body, _ := io.ReadAll(c.Request.Body)
    println(string(body))
}

Or if you just want to peek it in middleware, you can put it back after read:

func createOrUpdateInfluencer(c *gin.Context) {
    body, _ := io.ReadAll(c.Request.Body)
    println(string(body))

    c.Request.Body = io.NopCloser(bytes.NewReader(body))
}

Upvotes: 21

Related Questions