gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.19k stars 7.98k forks source link

Multipart form-data request with empty key for single file upload #3928

Open KaustubhPatange opened 5 months ago

KaustubhPatange commented 5 months ago

We're are migrating one of our micro-services written in NodeJS Javascript which handles all things related to upload into Go, thinking to use gin framework. However I've noticed a few things when doing a multipart upload.

Following is the basic code implementation

package main

import (
    "fmt"
    "net/http"

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

func main() {
    r := gin.Default()

    r.POST("/upload", func(c *gin.Context) {
        c.Request.ParseMultipartForm(32 << 20)
        fm, err := c.MultipartForm()
        if err != nil {
            c.String(http.StatusBadRequest, "Bad request, no file uploaded")
            return
        }

        fmt.Println(fm.File)

        c.String(http.StatusOK, "OK")
    })

    r.Run(":8081")
}

To my surprise it seems that when the "key" is not provided it fails to parse the form body. We did not face this issue with our current implementation in NodeJs Fastify framework, where request.file() gives you the first file in the multipart request.

Is there a way in Gin which has such similar effect, maybe grouping by form boundary?

JimChenWYU commented 1 month ago

https://github.com/golang/go/blob/master/src/mime/multipart/formdata.go#L124

image

because if the field name is empty, will be skip.


by the way, if you want to solve it, you can parse body data by yourself, reference to the following https://github.com/golang/go/blob/master/src/mime/multipart/formdata.go#L41

KaustubhPatange commented 1 month ago

We fixed it by refactoring all code to have a "key". But looking at this it would've made more sense to writing a custom parse body function.

Thanks for this.