在 Go 的 http 包中,如何获取 POST 请求上的查询字符串?

我使用 Go 中的 http包来处理 POST 请求。如何从 Request对象访问和解析查询字符串的内容?我无法从官方文件中找到答案。

239076 次浏览

QueryString 在 URL 中是 根据定义。您可以使用 req.URL(医生)访问请求的 URL。URL 对象有一个返回 Values类型的 Query()方法(医生) ,它只是 QueryString 参数的一个 map[string][]string

如果您要查找的是 POST 数据 以 HTML 格式提交,那么这(通常)是请求体中的键-值对。您的答案是正确的,您可以调用 ParseForm(),然后使用 req.Form字段来获得键-值对的映射,但是您也可以调用 FormValue(key)来获得特定键的值。如果需要,这将调用 ParseForm(),并获取值,而不管它们是如何发送的(例如,在查询字符串中还是在请求体中)。

下面是一个例子:

value := r.FormValue("field")

了解更多信息。关于 http 包,您可以访问其文档 给你FormValue基本上按照它找到的第一个值的顺序返回 POST 或 PUT 值,或 GET 值。

下面是如何访问 GET 参数的一个更具体的示例。Request对象有一个方法,可以为您解析它们,称为 质疑:

假设像 http://host:port/something?param1=b这样的请求 URL

func newHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET params were:", r.URL.Query())


// if only one expected
param1 := r.URL.Query().Get("param1")
if param1 != "" {
// ... process it, will be the first (only) if multiple were given
// note: if they pass in like ?param1=&param2= param1 will also be "" :|
}


// if multiples possible, or to process empty values like param1 in
// ?param1=&param2=something
param1s := r.URL.Query()["param1"]
if len(param1s) > 0 {
// ... process them ... or you could just iterate over them without a check
// this way you can also tell if they passed in the parameter as the empty string
// it will be an element of the array that is the empty string
}
}

还要注意“ Value 映射中的键[即 Query ()返回值]是区分大小写的。”

下面的文字来自官方文件。

表单包含经过解析的表单数据,包括 URL 字段的查询参数POST 或 PUT 表单数据。此字段只有在调用 ParseForm 之后才可用。

因此,下面的示例代码可以工作。

func parseRequest(req *http.Request) error {
var err error


if err = req.ParseForm(); err != nil {
log.Error("Error parsing form: %s", err)
return err
}


_ = req.Form.Get("xxx")


return nil
}

下面是一个简单实用的例子:

package main


import (
"io"
"net/http"
)
func queryParamDisplayHandler(res http.ResponseWriter, req *http.Request) {
io.WriteString(res, "name: "+req.FormValue("name"))
io.WriteString(res, "\nphone: "+req.FormValue("phone"))
}


func main() {
http.HandleFunc("/example", func(res http.ResponseWriter, req *http.Request) {
queryParamDisplayHandler(res, req)
})
println("Enter this in your browser:  http://localhost:8080/example?name=jenny&phone=867-5309")
http.ListenAndServe(":8080", nil)
}

enter image description here

有两种获得查询参数的方法:

  1. 使用 reqest.URL.Query ()
  2. 使用请求表格

在第二种情况下,必须小心,因为主体参数将优先于查询参数。有关获取查询参数的完整描述可以在这里找到

Https://golangbyexample.com/net-http-package-get-query-params-golang