【问题标题】:How to extract the post arguments in go server如何在 go server 中提取 post 参数
【发布时间】:2013-05-06 21:27:34
【问题描述】:

下面是一个用 go 写的服务器。

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
    fmt.Fprintf(w,"%s",r.Method)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

如何提取发送到localhost:8080/something URL 的POST 数据?

【问题讨论】:

    标签: http post get go


    【解决方案1】:
    package main
    
    import (
      "fmt"
      "log"
      "net/http"
      "strings"
    )
    
    
    func main() {
      // the forward slash at the end is important for path parameters:
      http.HandleFunc("/testendpoint/", testendpoint)
      err := http.ListenAndServe(":8888", nil)
      if err != nil {
        log.Println("ListenAndServe: ", err)
      }
    }
    
    func testendpoint(w http.ResponseWriter, r *http.Request) {
      // If you want a good line of code to get both query or form parameters
      // you can do the following:
      param1 := r.FormValue("param1")
      fmt.Fprintf( w, "Parameter1:  %s ", param1)
    
      //to get a path parameter using the standard library simply
      param2 := strings.Split(r.URL.Path, "/")
    
      // make sure you handle the lack of path parameters
      if len(param2) > 4 {
        fmt.Fprintf( w, " Parameter2:  %s", param2[5])
      }
    }
    

    您可以在 aapi 操场上运行代码here

    将此添加到您的访问网址:/mypathparameeter?param1=myqueryparam

    我想暂时离开上面的链接,因为它为您提供了一个运行代码的好地方,而且我相信能够看到它的实际运行很有帮助,但让我解释一些您可能想要的典型情况一个帖子参数。

    开发人员有几种典型的方式将发布数据拉到后端服务器,通常在从请求中拉取文件或大量数据时会使用多部分表单数据,所以我看不出这有什么关系,至少在问题的上下文中。他正在寻找帖子参数,这通常意味着表单帖子数据。通常表单发布参数以 Web 表单的形式发送到后端服务器。

    1. 当用户从 html 向 golang 提交登录表单或注册数据时,在这种情况下来自客户端的 Content Type 标头通常是 application/x-www-form-urlencoded,我相信这就是问题所在,这些将是表单后参数,使用 r.FormValue("param1") 提取。

    2. 1234563正文,内容类型标头 application/json。

    内容类型标头主要负责您将如何解析来自客户端的数据,我给出了 2 种不同内容类型的示例,但还有更多。

    【讨论】:

    • 这不是 OP 要问的,他是在问如何提取 POST 数据。
    • 将所有这些信息编辑到您的答案中,这将是对 OP 的更好反应。一个简单的代码 sn-p 是不够的,链接答案也有点不受欢迎,因为链接可能会损坏/丢失。
    • 现在这是个好建议,我编辑了我的答案,进一步的建议会有所帮助。我不熟悉此表单并想学习。
    • @Psychotechnopath 你们可能想在stackoverflow.com/help/how-to-answer 中更改关于如何回答问题的声明,因为这里说鼓励链接。老实说,我认为您有时需要链接来帮助描述。如果我不在基地,请告诉我。
    • " 但请在链接周围添加上下文,以便您的其他用户了解它是什么以及它为什么存在。始终引用重要链接的最相关部分,以防目标站点无法访问或永久离线。”。我只是说仅链接的答案很糟糕。
    【解决方案2】:

    对于普通请求:

    r.ParseForm()
    value := r.FormValue("value")
    

    对于多部分请求:

    r.ParseForm()
    r.ParseMultipartForm(32 << 20)
    file, _, _ := r.FormFile("file")
    

    【讨论】:

      【解决方案3】:

      对于 POSTPATCHPUT 请求:

      首先我们调用r.ParseForm(),它将POST请求正文中的任何数据添加到r.PostForm映射

      err := r.ParseForm()
      if err != nil {
          // in case of any error
          return
      }
      
      // Use the r.PostForm.Get() method to retrieve the relevant data fields
      // from the r.PostForm map.
      value := r.PostForm.Get("parameter_name")
      

      对于POSTGETPUT等(对于所有请求):

      err := r.ParseForm()
      if err != nil {
          // in case of any error
          return
      }
      
      // Use the r.Form.Get() method to retrieve the relevant data fields
      // from the r.Form map.
      value := r.Form.Get("parameter_name") // attention! r.Form, not r.PostForm 
      

      Form 方法

      相比之下,r.Form 映射为所有请求填充 (不管他们的 HTTP 方法),并包含来自的表单数据 任何请求正文和任何查询字符串参数。所以,如果我们的表格是 提交到/sn-p/create?foo=bar,我们也可以得到 通过调用 r.Form.Get("foo") 获取 foo 参数。请注意,在事件 发生冲突时,请求正文值将优先于 查询字符串参数。

      FormValuePostFormValue 方法

      net/http 包还提供了方法 r.FormValue() 和 r.PostFormValue()。这些本质上是调用的快捷函数 r.ParseForm() 为您,然后从中获取适当的字段值 r.Form 或 r.PostForm 分别。我建议避免使用这些快捷方式 因为它们会默默地忽略 r.ParseForm() 返回的任何错误。 这并不理想——这意味着我们的应用程序可能会遇到 错误和用户失败,但没有反馈机制让 他们知道。

      所有示例均来自关于 Go 的最佳书籍 - Let's Go! Learn to Build Professional Web Applications With Golang。这本书可以回答你所有的问题!

      【讨论】:

        【解决方案4】:

        像这样:

        func handler(w http.ResponseWriter, r *http.Request) {
            r.ParseForm()                     // Parses the request body
            x := r.Form.Get("parameter_name") // x will be "" if parameter is not set
            fmt.Println(x)
        }
        

        【讨论】:

        • 请注意,这似乎仅适用于 urlencoded 而不适用于多部分表单数据。
        • PS:这方面的文档目前很差,缺乏好的例子。 golang.org/pkg/net/http 只是说...
        • 是的,不需要那种 PS。
        【解决方案5】:

        要从发布请求中提取值,您必须首先调用r.ParseForm()。 [This][1] 解析来自 URL 的原始查询并更新 r.Form。

        对于 POST 或 PUT 请求,它还将请求正文解析为表单 并将结果放入 r.PostForm 和 r.Form 中。 POST 和 PUT 正文 参数优先于 r.Form 中的 URL 查询字符串值。

        现在您的r.From 是您的客户提供的所有值的映射。要提取特定值,您可以使用r.FormValue("&lt;your param name&gt;")r.Form.Get("&lt;your param name&gt;")

        您也可以使用r.PostFormValue

        【讨论】:

          【解决方案6】:

          引用http.Request的文档

          // 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.
          // The HTTP client ignores Form and uses Body instead.
          Form url.Values
          

          【讨论】:

          • 您能否举个具体的例子。我是新手,不知道怎么用。
          猜你喜欢
          • 2014-11-22
          • 1970-01-01
          • 2016-08-04
          • 2012-05-05
          • 1970-01-01
          • 1970-01-01
          • 2021-01-12
          • 2015-02-06
          • 1970-01-01
          相关资源
          最近更新 更多