Parsing Files and JSON from HTTP Requests in Go
When constructing an HTTP request from an AngularJS front end, you may encounter the need to parse both a file and JSON data. This can be challenging, especially when attempting to parse the JSON data from the request body.
Consider the following HTTP request payload:
Content-Disposition: form-data; name="file"; filename="Parent Handbook.pdf" Content-Type: application/pdf Content-Disposition: form-data; name="doc" {"title":"test","cat":"test cat","date":20142323}
In this scenario, "file" represents the PDF document, while "doc" contains the JSON data you wish to parse.
For parsing both the file and JSON data effectively, Go provides a suitable solution. Here's how you can achieve this:
Instead of assuming that r.Body contains the JSON data, you should utilize r.MultipartReader() to process both the PDF and JSON parts separately. This function provides a mime/multipart.Reader object that enables you to iterate through the different parts of the request using r.NextPart().
Here's an example of a revised 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() // No more parts if err == io.EOF { break } // Error occurred if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // PDF 'file' part 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 } } // 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 Parse Files and JSON from HTTP Requests in Go. For more information, please follow other related articles on the PHP Chinese website!