Home >Backend Development >Golang >How to Parse Files and JSON Data from an HTTP Request in Golang?
In a web application, it's common to receive both files and JSON data in an HTTP request. To successfully process these elements, it's essential to understand how to parse them effectively.
Consider a scenario where you have an AngularJS front end that sends a request to a Go backend. The request contains a file ("file") and JSON data ("doc"). Your goal is to parse both the PDF file and the JSON data from this request.
To resolve this issue, you need to separately process both the file and JSON data. By utilizing http.(*Request).MultipartReader() and iterating over the parts using NextPart(), you can extract and parse each element.
<code class="go">mr, err := r.MultipartReader() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }</code>
For each part in the multipart request:
<code class="go">part, err := mr.NextPart() if err == io.EOF { break } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }</code>
If the part is a file (part.FormName() == "file"):
<code class="go">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 }</code>
If the part contains JSON data (part.FormName() == "doc"):
<code class="go">jsonDecoder := json.NewDecoder(part) err = jsonDecoder.Decode(&doc) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }</code>
After parsing both file and JSON data, you can perform any necessary post-processing, such as saving it to a database or sending a response to the client.
The above is the detailed content of How to Parse Files and JSON Data from an HTTP Request in Golang?. For more information, please follow other related articles on the PHP Chinese website!