Home >Backend Development >Golang >How to Handle Multiple Request Parts in Go (PDF and JSON)?

How to Handle Multiple Request Parts in Go (PDF and JSON)?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 15:01:38301browse

How to Handle Multiple Request Parts in Go (PDF and JSON)?

Parsing File and JSON Data Simultaneously from an HTTP Request with Go

In this scenario, you aim to parse both a PDF document and JSON data from a multipart HTTP request form. The complication arises from the requirement to handle two distinct parts within a single request.

To efficiently handle this situation, consider utilizing Go's http.(*Request).MultipartReader() method. This method returns a mime/multipart.Reader object, which allows you to iterate over individual parts of the request using the r.NextPart() function.

Revising your handler function to incorporate this method would look something like this:

<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()

        // This is OK, no more parts
        if err == io.EOF {
            break
        }

        // Some error
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // PDF 'file' part
        if part.FormName() == "file" {
            doc.Url = part.FileName()
            fmt.Println("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 Handle Multiple Request Parts in Go (PDF and JSON)?. 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