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

时间:2016-11-20 20:00:58

标签: 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 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有什么问题? (还是跟我一起?)

1 个答案:

答案 0 :(得分:1)

您必须使用(使用" 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!"))
}