Home >Backend Development >Golang >How to Handle Multiple Request Parts in Go (PDF and JSON)?
Parsing File and JSON Data Simultaneously from an HTTP Request with Go
In this scenario, you aim to parse both a PDF document and JSON data from a multipart HTTP request form. The complication arises from the requirement to handle two distinct parts within a single request.
To efficiently handle this situation, consider utilizing Go's http.(*Request).MultipartReader() method. This method returns a mime/multipart.Reader object, which allows you to iterate over individual parts of the request using the r.NextPart() function.
Revising your handler function to incorporate this method would look something like this:
<code class="go">func (s *Server) PostFileHandler(w http.ResponseWriter, r *http.Request) { mr, err := r.MultipartReader() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } doc := Doc{} for { part, err := mr.NextPart() // This is OK, no more parts if err == io.EOF { break } // Some error if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // PDF 'file' part if part.FormName() == "file" { doc.Url = part.FileName() fmt.Println("URL:", part.FileName()) outfile, err := os.Create("./docs/" + part.FileName()) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer outfile.Close() _, err = io.Copy(outfile, part) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } // JSON 'doc' part if part.FormName() == "doc" { jsonDecoder := json.NewDecoder(part) err = jsonDecoder.Decode(&doc) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }</code>
The above is the detailed content of How to Handle Multiple Request Parts in Go (PDF and JSON)?. For more information, please follow other related articles on the PHP Chinese website!