Home  >  Article  >  Backend Development  >  How to Parse Files and JSON Data from an HTTP Request in Golang?

How to Parse Files and JSON Data from an HTTP Request in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 17:06:02785browse

How to Parse Files and JSON Data from an HTTP Request in Golang?

Parsing Files and JSON Data from an HTTP Request in Go

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.

The Problem

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.

The Solution

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.

Step 1: Create a Multipart Reader

<code class="go">mr, err := r.MultipartReader()
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}</code>

Step 2: Process Each Part

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>

Step 3: Extract File Data

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>

Step 4: Parse JSON Data

If the part contains JSON data (part.FormName() == "doc"):

<code class="go">jsonDecoder := json.NewDecoder(part)
err = jsonDecoder.Decode(&amp;doc)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}</code>

Step 5: Post-Processing

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn