"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-13
Browse:429

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

mr, err := r.MultipartReader()
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

Step 2: Process Each Part

For each part in the multipart request:

part, err := mr.NextPart()
if err == io.EOF {
    break
}
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

Step 3: Extract File Data

If the part is a file (part.FormName() == "file"):

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
}

Step 4: Parse JSON Data

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

jsonDecoder := json.NewDecoder(part)
err = jsonDecoder.Decode(&doc)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

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.

Release Statement This article is reprinted at: 1729747542 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3