I'm using Goa v3 to design an endpoint that allows me to upload files (more precisely, images) with a multipart/form-data
POST request.
I have declared the following Service
:
var _ = Service("images", func() {
HTTP(func() {
Path("/images")
})
Method("upload", func() {
HTTP(func() {
POST("/")
MultipartRequest()
})
Payload(func() {
Description("Multipart request Payload")
Attribute("File", Bytes, "File")
})
Result(ImageList)
})
})
I run the goa gen
and the goa example
commands to generate the boilerplate code. Apart from the cmd
directory, the example
code generates the images.go
main file and a multipart.go
file to declare the encoder and decoder logic, e.g.:
func ImagesUploadDecoderFunc(mr *multipart.Reader, p **images.UploadPayload) error {
// Add multipart request decoder logic here
return nil
}
I can use the mr.NextPart()
and obtain a reference to the image file apparently, but I'm still not sure how should I map this to the Bytes
field in the images.UploadPayload
type (or maybe I should declare another type of field to handle Files??).
I can't find any example in the Goa documentation.
Ok, I finally understood how the
multipart.Reader
works, and I came up with a solution.First let's clarify that differently from how Goa usually works (mapping 'automatically' the requests params with the
Payload
fields), withMultipartRequest()
, I have to make the mapping on my own, so thePayload
can actually have any structure.In my case, I re-defined my
Payload
structure as follows:In a nutshell, I want to support uploading several files, each with its mime-type, filename and data.
To achieve this, I implemented the
multipart.go
decoder function like this: