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

huangapple go评论114阅读模式
英文:

In Go's http package, how do I get the query string on a POST request?

问题

我正在使用Go语言的http包处理POST请求。我该如何访问和解析Request对象中的查询字符串内容?我在官方文档中找不到答案。

英文:

I'm using the httppackage from Go to deal with POST request. How can I access and parse the content of the query string from the Requestobject ? I can't find the answer from the official documentation.

答案1

得分: 183

这是一个更具体的示例,展示了如何访问GET参数。Request对象有一个方法可以帮助你解析它们,叫做Query

假设一个请求URL为 http://host:port/something?param1=b

func newHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Println("GET参数为:", r.URL.Query())
 
  // 如果只有一个参数
  param1 := r.URL.Query().Get("param1")
  if param1 != "" {
    // ... 处理它,如果有多个参数,它将是第一个(唯一的)
    // 注意:如果他们像这样传入:?param1=&param2=,param1也将是""
  }

  // 如果可能有多个参数,或者处理空值,比如在?param1=&param2=something中
  param1s := r.URL.Query()["param1"]
  if len(param1s) > 0 {
    // ... 处理它们 ... 或者你可以直接遍历它们而不进行检查
    // 这样你还可以判断他们是否将参数传入为空字符串
    // 空字符串将作为数组的一个元素存在
  }    
}

还要注意,“Values map中的键(即Query()的返回值)是区分大小写的。”

英文:

Here's a more concrete example of how to access GET parameters. The Request object has a method that parses them out for you called Query:

Assuming a request URL like 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=&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
  }    
}

Also note "the keys in a Values map [i.e. Query() return value] are case-sensitive."

答案2

得分: 180

一个查询字符串是在URL中的。您可以使用req.URL文档)访问请求的URL。URL对象有一个Query()方法(文档),它返回一个Values类型,它只是一个QueryString参数的map[string][]string

如果您要查找的是由HTML表单提交的POST数据([通常] 4),那么这通常是请求体中的键值对。您在回答中正确地指出,您可以调用ParseForm(),然后使用req.Form字段获取键值对的映射,但您也可以调用FormValue(key)来获取特定键的值。如果需要,这将调用ParseForm(),并获取无论如何发送的值(即在查询字符串中还是在请求体中)。

英文:

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

答案3

得分: 21

以下是一个例子:

value := r.FormValue("field")

有关http包的更多信息,您可以访问其文档这里FormValue基本上按顺序返回POST或PUT值,或者GET值,它找到的第一个值。

英文:

Below is an example:

value := r.FormValue("field")

for more info. about http package, you could visit its documentation here. FormValue basically returns POST or PUT values, or GET values, in that order, the first one that it finds.

答案4

得分: 10

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

  1. 使用reqeust.URL.Query()
  2. 使用request.Form

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

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

英文:

There are two ways of getting query params:

  1. Using reqeust.URL.Query()
  2. Using request.Form

In second case one has to be careful as body parameters will take precedence over query parameters. A full description about getting query params can be found here

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

答案5

得分: 9

这是一个简单的工作示例:

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("在浏览器中输入以下内容:http://localhost:8080/example?name=jenny&phone=867-5309")
    http.ListenAndServe(":8080", nil)
}
英文:

Here's a simple, working example:

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

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

答案6

得分: 6

以下文字来自官方文档。

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

因此,以下示例代码将起作用。

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

	if err = req.ParseForm(); err != nil {
		log.Error("解析表单错误:%s", err)
		return err
	}
	
	_ = req.Form.Get("xxx")

	return nil
}
英文:

Below words come from the official document.

> Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

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
}

huangapple
  • 本文由 发表于 2013年3月14日 19:17:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/15407719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定