go web 学习,学习到表单-处理表单的输入的时胡,和书上写的一样,但是运行却报错
go web 学习,学习到表单-处理表单的输入的时胡,和书上写的一样,但是运行却报错.
下面是代码和报错信息。
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request){
r.ParseForm()
fmt.Println(r.Form)
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!")
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //获取请求的方法
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
//请求的是登陆数据,那么执行登陆的逻辑判断
fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])
}
}
func main() {
http.HandleFunc("/", sayHelloName)
http.HandleFunc("/login", login)
err := http.ListenAndServe(":9090", nil)
if err != nil{
log.Fatal("ListenAddServer: ", err)
}
}
login.gtpl
<html>
<head>
<title></title>
</head>
<body>
<form action="/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="登陆">
</form>
</body>
</html>
目录结构:
demo1
main.go
login.gtpl
错误信息
method: GET
2019/10/22 15:19:22 http: panic serving 127.0.0.1:64117: runtime error: invalid memory address or nil pointer dereference
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc0000650e0)
D:/golang/src/net/http/server.go:1767 +0x140
panic(0x780880, 0xabfe80)
D:/golang/src/runtime/panic.go:679 +0x1c0
html/template.(*Template).escape(0x0, 0x0, 0x0)
D:/golang/src/html/template/template.go:95 +0x49
html/template.(*Template).Execute(0x0, 0x869920, 0xc000102000, 0x0, 0x0, 0x869a60, 0xc0000ca150)
D:/golang/src/html/template/template.go:119 +0x36
main.login(0x86f5e0, 0xc000102000, 0xc0000ee000)
E:/go_code/src/demo1/main/main.go:28 +0x34d
net/http.HandlerFunc.ServeHTTP(0x807338, 0x86f5e0, 0xc000102000, 0xc0000ee000)
D:/golang/src/net/http/server.go:2007 +0x4b
net/http.(*ServeMux).ServeHTTP(0xacfa00, 0x86f5e0, 0xc000102000, 0xc0000ee000)
D:/golang/src/net/http/server.go:2387 +0x1c4
net/http.serverHandler.ServeHTTP(0xc0000c4000, 0x86f5e0, 0xc000102000, 0xc0000ee000)
D:/golang/src/net/http/server.go:2802 +0xab
net/http.(*conn).serve(0xc0000650e0, 0x86fba0, 0xc0000cc000)
D:/golang/src/net/http/server.go:1890 +0x87c
created by net/http.(*Server).Serve
D:/golang/src/net/http/server.go:2927 +0x395
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
login.gtpl 这个文件你创建了吗?