我正在使用httpGo中的包来处理POST请求.如何从Request对象访问和解析查询字符串的内容?我无法从官方文档中找到答案.
mna*_*mna 132
根据定义,QueryString 在URL中.您可以使用req.URL(doc)访问请求的URL .URL对象有一个Query()方法(doc),它返回一个Values类型,它只是map[string][]stringQueryString参数的一个.
如果您要查找的是HTML表单提交的POST数据,那么这通常是请求正文中的键值对.你的答案是正确的,你可以调用ParseForm()然后使用req.Form字段来获取键值对的映射,但你也可以调用FormValue(key)以获取特定键的值.ParseForm()如果需要,它会调用,并获取值,无论它们是如何发送的(即在查询字符串中或在请求正文中).
rog*_*ack 104
这是一个如何访问GET参数的更具体的例子.该Request对象有一个方法可以为您解析它们,称为Query:
假设请求URL如http:// host:port/something?param1 = b
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=¶m2= param1 will also be "" :|
}
// if multiples possible, or to process empty values like param1 in
// ?param1=¶m2=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
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意"值映射中的键[即Query()返回值]区分大小写."
Muh*_*man 12
以下是一个例子:
value := r.FormValue("field")
Run Code Online (Sandbox Code Playgroud)
了解更多信息.关于http包,你可以在这里访问它的文档. FormValue基本上按顺序返回POST或PUT值或GET值,它是它找到的第一个值.
有两种获取查询参数的方法:
在第二种情况下必须小心,因为主体参数将优先于查询参数。可以在此处找到有关获取查询参数的完整说明
https://golangbyexample.com/net-http-package-get-query-params-golang
小智 5
以下文字来自官方文档。
表单包含解析的表单数据,包括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
}
Run Code Online (Sandbox Code Playgroud)
这是一个简单的工作示例:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128113 次 |
| 最近记录: |