如何在go服务器中提取post参数

foo*_*oty 9 post get http go

下面是一个用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)
}
Run Code Online (Sandbox Code Playgroud)

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

thw*_*hwd 23

像这样:

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)
}
Run Code Online (Sandbox Code Playgroud)

  • PS:这方面的文档目前很差,缺乏很好的例子.https://golang.org/pkg/net/http/只是说...... (4认同)

zzz*_*zzz 7

从文档中引用 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
Run Code Online (Sandbox Code Playgroud)

  • 你能不能更具体地举个例子。我是新手,我不明白如何使用它。 (4认同)

Ali*_*dov 5

对于POSTPATCHPUT请求:

\n\n

首先,我们调用r.ParseForm()它将 POST 请求正文中的所有数据添加到地图r.PostForm

\n\n
err := r.ParseForm()\nif err != nil {\n    // in case of any error\n    return\n}\n\n// Use the r.PostForm.Get() method to retrieve the relevant data fields\n// from the r.PostForm map.\nvalue := r.PostForm.Get("parameter_name")\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
err := r.ParseForm()\nif err != nil {\n    // in case of any error\n    return\n}\n\n// Use the r.Form.Get() method to retrieve the relevant data fields\n// from the r.Form map.\nvalue := r.Form.Get("parameter_name") // attention! r.Form, not r.PostForm \n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

方法Form

\n\n

相比之下,r.Form 映射针对所有请求(无论其 HTTP 方法如何)进行填充,并包含来自任何请求正文和任何查询字符串参数的表单数据。因此,如果我们的表单被提交到 /snippet/create?foo=bar,我们还可以通过调用 r.Form.Get("foo") 来获取 foo 参数的值。请注意,如果发生冲突,请求正文值将优先于查询字符串参数。

\n\n

方法FormValuePostFormValue方法

\n\n

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

\n
\n\n

所有示例均来自关于围棋的最佳书籍 - Let\'s Go! 学习使用 Golang 构建专业的 Web 应用程序。这本书可以解答你所有的疑问!

\n