0

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.

NicoNex
  • 469
  • 2
  • 5
  • 15
  • You can use one of the `multipart/*` content types. – Jonathan Hall Aug 25 '21 at 15:20
  • Definitely multipart. It is a bit whack due to having to specify a boundary which must not be contained within any of your files, but you can see an example here: https://stackoverflow.com/a/913749/593146 – Zyl Aug 25 '21 at 15:32
  • 1
    Note that if you don't intend for the API to be reachable via browser forms, you can also do anything else you can come up with instead. – Zyl Aug 25 '21 at 15:37
  • Does this answer your question? [Is it possible to upload multiple files at one shoot](https://stackoverflow.com/questions/63319613/is-it-possible-to-upload-multiple-files-at-one-shoot) –  Aug 25 '21 at 19:35

0 Answers0