首頁  >  文章  >  後端開發  >  如何在 Go 中處理多個請求部分(PDF 和 JSON)?

如何在 Go 中處理多個請求部分(PDF 和 JSON)?

Patricia Arquette
Patricia Arquette原創
2024-10-24 15:01:38206瀏覽

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

使用Go 同時解析來自HTTP 請求的文件和JSON 資料

在此場景中,您的目標是解析PDF 文件和JSON來自多部分HTTP 請求表單的資料。複雜性源自於需要在單一請求中處理兩個不同的部分。

為了有效地處理這種情況,請考慮利用 Go 的 http.(*Request).MultipartReader() 方法。此方法傳回一個 mime/multipart.Reader 對象,它允許您使用 r.NextPart() 函數迭代請求的各個部分。

修改處理程序函數以合併此方法將如下所示:

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

以上是如何在 Go 中處理多個請求部分(PDF 和 JSON)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn