去:在走常规
问题描述:
不能创建一个服务器当试图ListenAndServer
一展身手程序内我得到一个错误:去:在走常规
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/static/", myHandler)
go func() {
http.ListenAndServe("localhost:80", nil)
}()
fmt.Printf("we are here")
resp, _ := http.Get("localhost:80/static")
ans, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("response: %s", ans)
}
func myHandler(rw http.ResponseWriter, req *http.Request) {
fmt.Printf(req.URL.Path)
}
错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x48 pc=0x401102]
goroutine 1 [running]:
panic(0x6160c0, 0xc0420080a0)
c:/go/src/runtime/panic.go:500 +0x1af
main.main()
C:/gowork/src/exc/14.go:20 +0xc2
exit status 2
所有我想要的是创造一个http
服务器。然后测试它并从代码连接到它。 Go有什么问题? (或我吗?)
答
您必须使用(以“http://”,在这种情况下)
resp, _ := http.Get("http://localhost:80/static")
,并检查错误,然后使用响应,公正的情况下请求失败
resp, err := http.Get("http://localhost:80/static")
if err != nil {
// do something
} else {
ans, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("response: %s", ans)
}
另外,如果你想从你的处理程序得到任何响应,你必须在其中写一个响应。
func myHandler(rw http.ResponseWriter, req *http.Request) {
fmt.Printf(req.URL.Path)
rw.Write([]byte("Hello World!"))
}
'Get' URL应该是:'http:// localhost:80/static'。调试而不是忽略你应该处理的错误。 –
如果我忽略错误。为什么要去恐慌?如果我忽略错误,总是会发生什么? – Aminadav
取决于。在这种情况下,由于无效的'http.Get'调用,'resp.Body'不存在,所以抛出错误。与其他语言不同,Go不会引发异常,但如果函数返回一个错误,我们应该处理一个错误。 –