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)
关于下一步该做什么有什么建议吗?
谢谢!
| 归档时间: |
|
| 查看次数: |
2795 次 |
| 最近记录: |