I'm writing a HTTP REST API in go and what I want is to receive in a single POST request an array of files with an ID associated to each of them.
What's the best (or most common) approach to this problem?
Currently my code looks like this and handles just the file upload:
func handlePut(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
fmt.Fprintln(w, errorf("invalid request, expected POST got %s", r.Method))
return
}
// 1Mb in memory the rest on disk.
r.ParseMultipartForm(1_048_576)
if r.MultipartForm == nil {
fmt.Fprintln(w, errorf("no file provided"))
return
}
if len(r.MultipartForm.File) == 0 {
fmt.Fprintln(w, errorf("no file provided"))
return
}
for _, headers := range r.MultipartForm.File {
for _, h := range headers {
tmp, err := h.Open()
if err != nil {
log.Println("handlePut", "h.Open", err)
continue
}
fname := filepath.Base(h.Filename)
cnt, err := io.ReadAll(tmp)
tmp.Close()
// do something with cnt and fname
}
fmt.Fprintln(w, "some content")
}
}
This piece of code can be found here and the project is https://github.com/NicoNex/adam.