Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go:无法在Go例程中创建服务器_Go - Fatal编程技术网

Go:无法在Go例程中创建服务器

Go:无法在Go例程中创建服务器,go,Go,在go例程中尝试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

在go例程中尝试
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
服务器。然后测试它并从代码连接到它。围棋怎么了?(或者和我一起?

您必须使用(在本例中使用“http://”)

并在使用响应之前检查错误,以防请求失败

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
。要调试而不是忽略错误,您应该处理它们。如果我忽略错误。为什么要恐慌?如果我忽略了错误,总是会发生什么?这要看情况而定。在这种情况下,抛出错误是因为
resp.Body
由于无效的
http.Get
调用而不存在。与其他一些语言不同,Go从不引发异常,但如果函数返回一个异常,我们应该处理一个错误。
func myHandler(rw http.ResponseWriter, req *http.Request) {
    fmt.Printf(req.URL.Path)
    rw.Write([]byte("Hello World!"))
}