我在Go中编写了一个简单的Web应用程序,需要读取HTTP表单的值(用户名,密码)等。但是,我发现打印时这些值是空的。 len(r.Form)
和 len(r.Form["password"])
都返回 0。
在尝试读取字段之前,我已经在应用程序中调用了r.ParseForm()
,并且我正在使用Postman发送请求。在 Linux 和 macOS 上都经过测试。
我用来测试的代码是Astaxie golang网络教程中的一些示例代码。我附上了我的邮递员请求。到目前为止,它看起来像这样:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
// attention: If you do not call ParseForm method, the following data can not be obtained form
fmt.Println(r.Form) // print information on server side.
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!") // write data to response
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //get request method
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
r.ParseForm()
time.Sleep(3 * time.Second)
// logic part of log in
fmt.Println("username:", len(r.Form))
fmt.Println("password:", len(r.Form["password"]))
}
}
func main() {
http.HandleFunc("/", sayhelloName) // setting router rule
http.HandleFunc("/login", login)
err := http.ListenAndServe(":9090", nil) // setting listening port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
关于下一步该怎么做的任何建议?
谢谢!
邮递员请求中的内容类型从form-data
更改为x-www-form-urlencoded
因为根据r.ParseForm()
上的文档,除非x-www-form-urlencoded
,否则不会解析正文
对于其他 HTTP 方法,或者当内容类型不是 application/x-www-form-urlencoded,请求正文未被读取,并且 r.PostForm 初始化为非 nil 的空值。
我建议您首先检查内容类型,然后根据请求读取表单数据。FormValue("示例")如果您使用表单,请始终检查键在映射中是否有效,如果您不这样做,则会产生运行时错误。
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //get request method
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
fmt.Println("username:", r.FormValue("username"))
fmt.Println("password:", r.FormValue("password"))
}
}