r.From["username"] 给出空值

r.From["username"] giving empty values

我使用 golang 编写了一个小型网络应用程序

go version go1.7.4 linux/amd64 Go Code:

r.ParseForm()
        // logic part of log in
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])

    
HTML template
<body>
    <div class="container">
        <h1>Login In</h1>
        <form action="/login" method="POST">
            <div class="form-group">
                <label for="username">User Name</label>
                <input type="text" class="form-control" name="username" placeholder="Please enter your user name">
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control" name="password" placeholder="Please enter your password">
            </div>
            <button type="submit" class="btn btn-success">Login</button>
        </form>
    </div>
</body>

当我使用

打印时
requestbody, _ := ioutil.ReadAll(r.Body)
log.Println("request body is", string(requestbody))

它正在打印正确的值以及输入的用户名和密码。 但是当我尝试使用 r.Form 打印它时,它给出了空值。 这种方法有什么问题吗?

func loginHandler(w http.ResponseWriter, r *http.Request) {
    log.Println("loginHandler")
    log.Println("request url is", r.RequestURI)
    log.Println("request method", r.Method)
    requestbody, _ := ioutil.ReadAll(r.Body)
    log.Println("request body is", string(requestbody))
    if r.Method == "POST" {
        r.ParseForm()
        // logic part of log in
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])
        us, err := globalSessions.SessionStart(w, r)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        w.Header().Set("Location", "/auth")
        w.WriteHeader(http.StatusFound)
        return
    }
    outputHTML(w, r, "static/login.html")
}

评论下面的代码:

requestbody, _ := ioutil.ReadAll(r.Body)

因为 Request.Body 的类型是 ReadCloser 会清空 r.Body.

仅供参考,