Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieving posted files using Golang Gin

Tags:

file-upload

go

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"}'
like image 918
Aaron Kenny Avatar asked Aug 03 '15 16:08

Aaron Kenny


2 Answers

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)
        }   
    }
like image 155
Kunal Jha Avatar answered Nov 01 '22 14:11

Kunal Jha


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)
}
like image 34
Alex Netkachov Avatar answered Nov 01 '22 15:11

Alex Netkachov