1

I have written an small web app using 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>

When I am printing using

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

it's printing correct values along with entered username and password. But when I tried to print it using r.Form it's giving empty value. Is anything wrong in this approach?

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")
}
I159
  • 29,741
  • 31
  • 97
  • 132
Vijay Kumar
  • 597
  • 2
  • 8
  • 27

1 Answers1

3

Comment the code below:

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

Because Request.Body's type is ReadCloser that will empty r.Body.

FYI, Golang read request body

Community
  • 1
  • 1
tanglong
  • 278
  • 2
  • 11