美文网首页
如何在 Go 中发送表单请求

如何在 Go 中发送表单请求

作者: 51reboot | 来源:发表于2019-12-24 11:30 被阅读0次

通常我们与第三方交互使用的是 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]

作者:宋佳洋
51reboot K8s课程1.18日开课,详情WeChat;17812796384 去了解

相关文章

  • 如何在 Go 中发送表单请求

    通常我们与第三方交互使用的是 json,但偶尔也会遇到要求使用表单方式来提交数据,故今天我们就一起来学习下如何在 ...

  • 发送网络请求

    1.表单发送请求 1.表单发送get请求 说明: 在form表单中通过action来设置请求的服务器地址. 默认情...

  • Laravel 5.4--Validate (表单验证) 使用实

    1.视图中的表单 2.控制器中验证数据 表单的发送post请求,到test路由中 发送了_token, code,...

  • Go: 使用PUT发送Form Data

    我使用Go实现了一个PUT接口,在浏览器中可以使用ajax发送请求: 但是使用Go写test时,发送的请求却接收不...

  • AJAX

    1. 如何发送请求 通过form表单发送请求(包括get请求和post请求),会刷新页面或新开页面 通过a链接发送...

  • 利用Go net/http发送Restful请求

    最近工作中涉及到了使用Go来发送restful请求,因为Go默认的http只提供GO&PATCH两种请求,其余类型...

  • vue-resource 编码技巧

    下面列举了一些公共的用例。 表单数据 使用 FormData 发送表单数据。 中止请求 当有新的请求准备发送时可以...

  • HttpClient 发送 GET、POST、PUT、Delet

    本文示例是在 httpclient4.3.6 下进行的测试。#### 发送Get请求: 发送Post请求,同表单P...

  • strict-origin-when-cross-origin

    提交表单发送ajax请求时,chrome 请求返回Referrer Policy: strict-origin-w...

  • axios如何取消接口请求

    vue项目,如何在axios中取消已经发送的请求呢? 原生js的abort()这个方法 在axios中取消接口请求...

网友评论

      本文标题:如何在 Go 中发送表单请求

      本文链接:https://www.haomeiwen.com/subject/unmdnctx.html