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)
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.
Most helpful comment
See example here in
developbranch:https://github.com/gin-gonic/gin/blob/develop/examples/upload-file/single/main.go