下面是一个用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)
从文档中引用 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)
对于POST、PATCH和PUT请求:
\n\n首先,我们调用r.ParseForm()它将 POST 请求正文中的所有数据添加到地图r.PostForm中
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")\nRun Code Online (Sandbox Code Playgroud)\n\n对于POST、GET、PUT等(对于所有请求):
\n\nerr := 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 \nRun Code Online (Sandbox Code Playgroud)\n\n\n\n\n方法
\n\nForm相比之下,r.Form 映射针对所有请求(无论其 HTTP 方法如何)进行填充,并包含来自任何请求正文和任何查询字符串参数的表单数据。因此,如果我们的表单被提交到 /snippet/create?foo=bar,我们还可以通过调用 r.Form.Get("foo") 来获取 foo 参数的值。请注意,如果发生冲突,请求正文值将优先于查询字符串参数。
\n\n方法
\n\nFormValue和PostFormValue方法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
所有示例均来自关于围棋的最佳书籍 - Let\'s Go! 学习使用 Golang 构建专业的 Web 应用程序。这本书可以解答你所有的疑问!
\n