143

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

4

6 回答 6

170

根据定义, QueryString位于 URL 中。您可以使用req.URL( doc ) 访问请求的 URL。URL 对象有一个返回类型的Query()方法 ( docValues ),该类型只是map[string][]stringQueryString 参数中的一个。

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

于 2013-03-14T12:03:54.180 回答
160

下面是一个更具体的示例,说明如何访问 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=&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
  }    
}

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

于 2015-03-24T16:09:08.693 回答
20

下面是一个例子:

value := r.FormValue("field")

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

于 2014-01-09T07:37:39.730 回答
10

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

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

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

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

于 2019-11-13T17:11:15.027 回答
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("Enter this in your browser:  http://localhost:8080/example?name=jenny&phone=867-5309")
    http.ListenAndServe(":8080", nil)
}

在此处输入图像描述

于 2017-06-22T02:16:59.450 回答
6

以下文字来自官方文档。

表单包含解析后的表单数据,包括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
}
于 2017-06-05T02:13:32.493 回答