import (
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
//注意:如果没有调用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!") //这个写入到w的是输出到客户端的
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //获取请求的方法
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
log.Println(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("ListenAndServe: ", err)
return
}
}
访问 http://127.0.0.1:9090/ 正常
再http://127.0.0.1:9090/login
就报错信息:
2016/09/08 21:27:10 http: panic serving 127.0.0.1:57871: runtime error: invalid memory address or nil pointer dereference
goroutine 8 [running]:
net/http.(*conn).serve.func1(0xc8200d0780)
/usr/local/go/src/net/http/server.go:1389 +0xc1
panic(0x39d800, 0xc82000a0a0)
/usr/local/go/src/runtime/panic.go:443 +0x4e9
html/template.(*Template).escape(0x0, 0x0, 0x0)
/usr/local/go/src/html/template/template.go:79 +0x3c
html/template.(*Template).Execute(0x0, 0x945880, 0xc8201340d0, 0x0, 0x0, 0x0, 0x0)
/usr/local/go/src/html/template/template.go:101 +0x34
main.login(0x9457f8, 0xc8201340d0, 0xc8201082a0)
/Users/eastsheen/dxyang/go_project/src/MyGoProject/test_web.go:86 +0x29f
net/http.HandlerFunc.ServeHTTP(0x4c8300, 0x9457f8, 0xc8201340d0, 0xc8201082a0)
/usr/local/go/src/net/http/server.go:1618 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc820012de0, 0x9457f8, 0xc8201340d0, 0xc8201082a0)
/usr/local/go/src/net/http/server.go:1910 +0x17d
net/http.serverHandler.ServeHTTP(0xc8200d0080, 0x9457f8, 0xc8201340d0, 0xc8201082a0)
/usr/local/go/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc8200d0780)
/usr/local/go/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2137 +0x44e
t, _ := template.ParseFiles("login.gtpl")
这里出错了嘛,很简单,把那个信邦掉的err打出来看看是什么就知道了。
估计,是找不到模板文件