无法在Go协程中创建服务器。

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

Go: cannot create a server in go routine

问题

尝试在Go协程中使用ListenAndServe时出现错误:

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出了什么问题?(或者是我的问题?)

英文:

When trying to ListenAndServer inside a go routine I get an error:

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)
}

The error:

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

All I want is to create an http server. And then test it and connect to it from the code. What's wrong with Go? (or with me?)

答案1

得分: 1

你必须使用(在这种情况下)带有"http://"的方式:

resp, _ := http.Get("http://localhost:80/static")

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

resp, err := http.Get("http://localhost:80/static")
if err != nil {
    // 处理错误
} 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!"))
}
英文:

You must use (with "http://" in this case)

resp, _ := http.Get("http://localhost:80/static")

and check the errors before use the response, just in case the request fails

resp, err := http.Get("http://localhost:80/static")
if err != nil {
    // do something
} else {
    ans, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("response: %s", ans)
}

Also, if you want to get any response from your handler, you have to write a response in it.

func myHandler(rw http.ResponseWriter, req *http.Request) {
    fmt.Printf(req.URL.Path)
    rw.Write([]byte("Hello World!"))
}

huangapple
  • 本文由 发表于 2016年11月21日 04:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/40708750.html
匿名

发表评论

匿名网友

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

确定