Go HTTP 表单解析 - 返回空切片/空值?

Lar*_*hen 2 forms parsing http go

我用 Go 编写了一个简单的 Web 应用程序,需要读取 HTTP 表单的值(用户名、密码)等。但是,我发现打印时这些值是空的。len(r.Form)并且len(r.Form["password"])都返回 0。

r.ParseForm()在尝试读取字段之前我已经调用了应用程序,并且我正在使用 Postman 发送请求。在 Linux 和 macOS 上进行了测试。

我用来测试的代码是 Astaxie golang Web 教程中的一些示例代码。我已附上我的邮递员请求。到目前为止看起来像这样:

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

关于下一步该做什么有什么建议吗?

谢谢!

gra*_*ish 6

尝试将 Postman 请求中的内容类型从 更改form-datax-www-form-urlencoded

因为根据body上的文档,r.ParseForm()除非它是,否则不会被解析x-www-form-urlencoded

对于其他 HTTP 方法,或者当 Content-Type 不是 application/x-www-form-urlencoded 时,不会读取请求 Body,并且 r.PostForm 会初始化为非 nil 的空值。