r。来自["用户名"]给出空值

时间:2017-04-24 06:11:12

标签: html go html-parsing beego

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

  

go go go7.7.4 linux / amd64   转码:

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>
&#13;
&#13;
&#13;

使用

进行打印时
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")
}

1 个答案:

答案 0 :(得分:3)

评论以下代码:

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

由于Request.Body的{​​{1}}类型为ReadCloser,因此会r.Body

仅供参考,Golang read request body