Simultaneously Parsing a PDF File and JSON Data from a Single HTTP Request in Go
When handling HTTP requests containing multipart form data, it can be necessary to parse both a file and JSON data from the same request. A common example is a form where users can upload a document (PDF) and provide additional data (JSON) related to the file.
To achieve this in Go, the r.ParseMultipartForm function is insufficient as it only parses multipart data. To handle both the file and JSON data separately, the r.MultipartReader function is required.
Solution:
The r.MultipartReader function returns a multipart.Reader object that allows iterating over each part of the multipart form data using the r.NextPart function. This enables us to process each part individually, distinguishing between the file part and the JSON part.
Here's an updated version of the handler function:
<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() if err == io.EOF { break } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if part.FormName() == "file" { doc.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 } } 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 Parse Both a PDF File and JSON Data from a Single HTTP Request in Go?. For more information, please follow other related articles on the PHP Chinese website!