如何在 Go 中傳送表單請求

smallfish1發表於2018-03-06

通常我們與第三方互動使用的是 json 格式,但偶爾也會遇到要求使用表單方式來提交資料,故今天我們就一起來學習下如何在 Go 中傳送表單請求。

準備工作

首先我們有這樣一段測試程式碼來接收 POST 請求,並返回其接收到的欄位資訊。

package main

import (
    "fmt"
    "log"
    "net/http"
)

func urlencodedHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        log.Printf("r.ParseForm(): %v", err)
        return
    }

    result := ""
    for k, v := range r.Form {
        result += fmt.Sprintf("%s:%v\n", k, v)
    }

    fmt.Fprintf(w, result)
}

func multipartHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseMultipartForm(4 * 1024 * 1024)
    if err != nil {
        log.Printf("r.ParseForm(): %v", err)
        return
    }

    result := ""
    for k, v := range r.MultipartForm.Value {
        result += fmt.Sprintf("%s:%v\n", k, v)
    }

    for k, v := range r.MultipartForm.File {
        result += fmt.Sprintf("%s:%v\n", k, v)
    }

    fmt.Fprintf(w, result)
}

func main() {
    http.HandleFunc("/urlencoded", urlencodedHandler)
    http.HandleFunc("/multipart", multipartHandler)

    log.Fatal(http.ListenAndServe(":8080", nil))
}

傳送 urlencoded 請求

urlencoded 主要用於純文字請求,程式碼如下:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
)

func main() {
    payload := url.Values{}
    payload.Set("foo", "a")
    payload.Add("foo", "b")
    payload.Set("foo2", "c")

    req, err := http.NewRequest(http.MethodPost,
                            "http://localhost:8080/urlencoded",
                            strings.NewReader(payload.Encode()))
    if err != nil {
        return
    }

    req.Header.Add("Content-Type",
                  "application/x-www-form-urlencoded; param=value")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return
    }

    defer resp.Body.Close()

    data, _ := ioutil.ReadAll(resp.Body)

    fmt.Println(string(data))
}

執行 go run urlencoded.go 輸出結果為:

foo2:[c]
foo:[a b]

傳送 multipart 請求

multipart 主要用於傳送檔案上傳的請求,程式碼如下:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "mime/multipart"
    "net/http"
)

func main() {
    buf := new(bytes.Buffer)

    writer := multipart.NewWriter(buf)
    writer.WriteField("foo", "a")
    writer.WriteField("foo", "b")

    part, err := writer.CreateFormFile("tmp.png", "tmp.png")
    if err != nil {
        return
    }

    fileData := []byte("hello,world")  // 此處內容可以來自本地檔案讀取或雲端儲存
    part.Write(fileData)

    if err = writer.Close(); err != nil {
        return
    }

    req, err := http.NewRequest(http.MethodPost,
                              "http://localhost:8080/multipart",
                              buf)
    if err != nil {
        return
    }

    req.Header.Add("Content-Type", writer.FormDataContentType())

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return
    }

    defer resp.Body.Close()

    data, _ := ioutil.ReadAll(resp.Body)

    fmt.Println(string(data))
}

執行 go run multipart.go 輸出結果為:

foo:[a b]
tmp.png:[0xc420082410]

更多閱讀,請關注

相關文章