Gin: how to fetch binary post data?

Created on 29 Mar 2017  路  5Comments  路  Source: gin-gonic/gin

how to fetch binary post data?
in official go package, I can fetch the data in the following code, how can do it in gin?

    body := Request.Body
    data, _ := ioutil.ReadAll(body)

Most helpful comment

See example here in develop branch:

https://github.com/gin-gonic/gin/blob/develop/examples/upload-file/single/main.go

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"

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

func main() {
    router := gin.Default()
    router.Static("/", "./public")
    router.POST("/upload", func(c *gin.Context) {
        name := c.PostForm("name")
        email := c.PostForm("email")

        // Source
        file, _ := c.FormFile("file")
        src, _ := file.Open()
        defer src.Close()

        // Destination
        dst, _ := os.Create(file.Filename)
        defer dst.Close()

        // Copy
        io.Copy(dst, src)

        c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email))
    })
    router.Run(":8080")
}

All 5 comments

See example here in develop branch:

https://github.com/gin-gonic/gin/blob/develop/examples/upload-file/single/main.go

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"

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

func main() {
    router := gin.Default()
    router.Static("/", "./public")
    router.POST("/upload", func(c *gin.Context) {
        name := c.PostForm("name")
        email := c.PostForm("email")

        // Source
        file, _ := c.FormFile("file")
        src, _ := file.Open()
        defer src.Close()

        // Destination
        dst, _ := os.Create(file.Filename)
        defer dst.Close()

        // Copy
        io.Copy(dst, src)

        c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, name, email))
    })
    router.Run(":8080")
}

@appleboy Thanks for you reply! but the code, such as name := c.PostForm("name"), seems it needs the post data must have a key name, it does not work without such key.

I use the following code to test, how to obtain the data aGVsbG8gd29ybGQ

    curl -d "aGVsbG8gd29ybGQ" http://127.0.0.1:8080

@appleboy it seems gin lack the api the fetch the raw data, my application needs to interact with another system design by another system, so I implement it in the context.go, i think such simple api should provide by gin.

func (c *Context) GetRawData() ([]byte, error) {
    body := c.Request.Body
    return ioutil.ReadAll(body)
}

@buf1024 Good catch. I will make new PR.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cxk280 picture cxk280  路  3Comments

ghost picture ghost  路  3Comments

oryband picture oryband  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

xpbliss picture xpbliss  路  3Comments