Home > Article > Backend Development > How to Effectively Parse Multi-Source Data in HTTP Requests with Go?
Parsing File and JSON Data from a Single HTTP Request with Go
Parsing data from multiple sources within a single HTTP request can be challenging. In this case, we're receiving both a PDF file and JSON data as separate parts. To effectively handle this scenario, Go provides the multipart/form-data package.
Solution:
The key to resolving this issue is to use r.MultipartReader(). This function returns a mime/multipart.Reader object, allowing us to iterate over each part of the request and process them individually. Here's the modified code:
<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() // End of parts if err == io.EOF { break } // Handle PDF 'file' part if part.FormName() == "file" { // ... PDF processing code } // Handle 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 } // ... JSON processing code } } // ... Database insertion and response handling code }</code>
Using this approach, we can separately parse the PDF file and JSON data, ensuring both parts of the request are processed correctly.
The above is the detailed content of How to Effectively Parse Multi-Source Data in HTTP Requests with Go?. For more information, please follow other related articles on the PHP Chinese website!