How to Parse Files and JSON from HTTP Requests in Go

DDD
Release: 2024-10-24 22:12:02
Original
794 people have browsed it

How to Parse Files and JSON from HTTP Requests in Go

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}
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!