I'm using the Golang framework Gin for a while now with no issues but I now need to process images posted to my API.
I can probably figure out how to deal with validating, resizing and storing the image but for now I'm just struggling to figure out how to grab the posted file and assign it to a variable.
I've looked at the Gin API docs but nothing is jumping out at me.
I'm curling my API as follows (this might be wrong?)...
$ time curl -X POST --form [email protected] -H "Content-Type: application/json" --cookie 'session=23423v243v25c08efb5805a09b5f288329003' "http://127.0.0.1:8080/v1.0/icon" --form data='{"json_name":"test json name","title":"Test","url":"http://sometest.com"}'
I will try to just answer the retrieving the filename and assigning it to the variable, because handling the json part is already taken care by @AlexAtNet. Let me know if this works for you
func (c *gin.Context) {
file, header , err := c.Request.FormFile("upload")
filename := header.Filename
fmt.Println(header.Filename)
out, err := os.Create("./tmp/"+filename+".png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
log.Fatal(err)
}
}
Try to get the HTTP request from the gin.Context and read from its Body property:
func(c *gin.Context) {
decoder := json.NewDecoder(c.Request.Body)
var t struct {
Name string `json:"json_name"`
Title string `json:"title"`
Url string `json:"url"`
}
err := decoder.Decode(&t)
if err != nil {
panic()
}
log.Println(t)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With