错误:获取页面请求

huangapple go评论72阅读模式
英文:

Error GET page request

问题

我是你的中文翻译助手,以下是代码的翻译:

我刚开始学习Golang,尝试创建一个简单的Web服务器,但在GET请求中遇到了错误。以下是代码:

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 World!") // 写入响应数据
}

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 {
		r.ParseForm()
		// 登录逻辑部分
		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)
	}
}

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 文件与源代码文件位于同一文件夹中。

<details>
<summary>英文:</summary>

I&#39;m new to Golang and I&#39;m trying to create a simple web server but I&#39;m getting an error in a GET request. This is the code:

    import (
    	&quot;fmt&quot;
    	&quot;html/template&quot;
    	&quot;log&quot;
    	&quot;net/http&quot;
    	&quot;strings&quot;
    )
    
    func sayhelloName(w http.ResponseWriter, r *http.Request) {
    	r.ParseForm() 
    	fmt.Println(r.Form) // print information on server side.
    	fmt.Println(&quot;path&quot;, r.URL.Path)
    	fmt.Println(&quot;scheme&quot;, r.URL.Scheme)
    	fmt.Println(r.Form[&quot;url_long&quot;])
    	for k, v := range r.Form {
    		fmt.Println(&quot;key:&quot;, k)
    		fmt.Println(&quot;val:&quot;, strings.Join(v, &quot;&quot;))
    	}
    	fmt.Fprintf(w, &quot;Hello Worrld!&quot;) // write data to response
    }
    
    func login(w http.ResponseWriter, r *http.Request) {
    	fmt.Println(&quot;method:&quot;, r.Method) //get request method
    	if r.Method == &quot;GET&quot; {
    		t, _ := template.ParseFiles(&quot;login.gtpl&quot;)
    		t.Execute(w, nil)
    	} else {
    		r.ParseForm()
    		// logic part of log in
    		fmt.Println(&quot;username:&quot;, r.Form[&quot;username&quot;])
    		fmt.Println(&quot;password:&quot;, r.Form[&quot;password&quot;])
    	}
    }
    
    func main() {
    	http.HandleFunc(&quot;/&quot;, sayhelloName) // setting router rule
    	http.HandleFunc(&quot;/login&quot;, login)
    	err := http.ListenAndServe(&quot;:9090&quot;, nil) // setting listening port
    	if err != nil {
    		log.Fatal(&quot;ListenAndServe: &quot;, err)
    	}
    }
`sayhelloName` works but not the `login` function. This is the output error:  

    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&#39;s in the same folder of source code file

</details>


# 答案1
**得分**: 3

始终处理错误

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

如果这失败了怎么办?那么`t`将为nil,你将得到相同的错误。

<details>
<summary>英文:</summary>

Always handle your errors

     t, _ := template.ParseFiles(&quot;login.gtpl&quot;)

What if this fails? Then `t` is nil and you get the same error

</details>



# 答案2
**得分**: 0

1. 不要忽略从template.ParseFiles返回的错误。
2. 将包括目录在内的路径放入template.ParseFiles中。

<details>
<summary>英文:</summary>

1. don&#39;t ignore error returned from template.ParseFiles
2. put path including directory into template.ParseFiles 

</details>



huangapple
  • 本文由 发表于 2015年10月18日 18:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/33196989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定