9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ginでリクエストボディをstringで受け取る

Last updated at Posted at 2018-08-21

リクエストボディを構造体にマッピングする以前に、どんなリクエストが来ているのか知るためにstringで見たいときがある。

package main

import (
        "fmt"
        "github.com/gin-gonic/gin"
)

func main() {
        router := gin.New()

        router.POST("hoge", func(c *gin.Context) {
                buf := make([]byte, 2048)
                n, _ := c.Request.Body.Read(buf)
                b := string(buf[0:n])
                fmt.Println(b)

                c.Status(200)
        })

        router.Run()
}

なお上のコードだと c.Request.Body のストリームを読み切ってしまうので、それがいやならば以下の記事のようにストリームに対してデータを書き戻すような実装をする必要がある。

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?