2015-10-18 216 views
-1

我是Golang的新手,我正嘗試創建一個簡單的Web服務器,但在GET請求中出現錯誤。這是代碼:錯誤GET頁面請求

import (
    "fmt" 
    "html/template" 
    "log" 
    "net/http" 
    "strings" 
) 

func sayhelloName(w http.ResponseWriter, r *http.Request) { 
    r.ParseForm() 
    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 Worrld!") // 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() 
     // logic part of log in 
     fmt.Println("username:", r.Form["username"]) 
     fmt.Println("password:", 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) 
    } 
} 

sayhelloName作品,但不是login功能。這是輸出錯誤:

method: GET 
2015/10/18 12:46:28 http: panic serving 127.0.0.1:51714: runtime error: invalid memory address or nil pointer dereference 
goroutine 6 [running]: 
net/http.(*conn).serve.func1(0x1247aa20, 0xaf5380, 0x12490390) 
    c:/go/src/net/http/server.go:1287 +0xa2 
html/template.(*Template).escape(0x0, 0x0, 0x0) 
    c:/go/src/html/template/template.go:79 +0x37 
html/template.(*Template).Execute(0x0, 0xaf54e8, 0x12530080, 0x0, 0x0, 0x0, 0x0) 
    c:/go/src/html/template/template.go:101 +0x2b 
main.login(0xaf5468, 0x12530080, 0x124f6620) 
    C:/Users/Fabio/Go/hello.go:30 +0x209 
net/http.HandlerFunc.ServeHTTP(0x7462e4, 0xaf5468, 0x12530080, 0x124f6620) 
    c:/go/src/net/http/server.go:1422 +0x34 
net/http.(*ServeMux).ServeHTTP(0x1252a020, 0xaf5468, 0x12530080, 0x124f6620) 
    c:/go/src/net/http/server.go:1699 +0x133 
net/http.serverHandler.ServeHTTP(0x12476480, 0xaf5468, 0x12530080, 0x124f6620) 
    c:/go/src/net/http/server.go:1862 +0x156 
net/http.(*conn).serve(0x1247aa20) 
    c:/go/src/net/http/server.go:1361 +0xc05 
created by net/http.(*Server).Serve 
    c:/go/src/net/http/server.go:1910 +0x343 

login.gptl it's in the same folder of source code file 
從template.ParseFiles返回

回答

3

務必抓住你的錯誤

t, _ := template.ParseFiles("login.gtpl") 

如果失敗會怎麼樣?然後t是零,你會得到相同的錯誤

+1

建立在此:請記住,如果您使用'go run',那麼程序可能不會從您的模板運行在同一目錄中。更好的方法是a)使用絕對路徑和b)在main()中分析模板,而不是在每個處理程序中(這意味着您在每個請求中都從磁盤讀取)。 – elithrar

0
  1. 不要忽略錯誤
  2. 放路徑包括目錄到template.ParseFiles