英文:
Golang http.Get()
问题
我正在尝试编写一个基本的HTTP服务器示例。我可以使用curl localhost:8080
进行访问,但无法使用客户端脚本中的http.Get("127.0.0.1:8080")
与服务器进行联系。我做错了什么?
server.go:
import "fmt"
import "net/http"
func join(w http.ResponseWriter, req *http.Request) {
fmt.Println("有人加入")
}
func main() {
fmt.Println("监听端口8080...")
http.HandleFunc("/join", join)
http.ListenAndServe(":8080", nil)
}
client.go:
import "net/http"
http.Get("127.0.0.1:8080/join")
你的代码看起来没有问题。但是在客户端脚本中,你需要在URL前面添加http://
,即http.Get("http://127.0.0.1:8080/join")
。这样才能正确地与服务器进行通信。
英文:
I'm trying to write a basic http server example. I can curl localhost:8080
, but can't contact the server with http.Get("127.0.0.1:8080")
from the client script. What am I doing wrong?
server.go:
import "fmt"
import "net/http"
func join(w http.ResponseWriter, req *http.Request) {
fmt.Println("Someone joined")
}
func main() {
fmt.Println("Listening on port 8080...")
http.HandleFunc("/join", join)
http.ListenAndServe(":8080", nil)
}
client.go:
import "net/http"
http.Get("127.0.0.1:8080/join")
答案1
得分: 7
尝试使用http.Get("http://127.0.0.1:8080/join")
。注意其中的"http:"。另外,检查错误信息,它会告诉你问题所在。
resp, err := http.Get("http://127.0.0.1:8080/join")
if err != nil {
log.Fatal(err)
}
英文:
Try http.Get("http://127.0.0.1:8080/join")
. Note the "http:". Also, check the error. It will tell you what the problem is.
resp, err := http.Get("http://127.0.0.1:8080/join")
if err != nil {
log.Fatal(err)
}
答案2
得分: 2
你没有指定方案,请尝试使用http.Get("http://127.0.0.1:8080/join")
。
http.Get
和许多其他Go函数一样,会返回错误。所以如果你的代码是这样写的:
_, err := http.Get("127.0.0.1:8080/join")
if err != nil {
fmt.Println(err)
}
你会看到以下错误信息:
Get 127.0.0.1:8080/join: unsupported protocol scheme ""
英文:
You have't specified the scheme, try http.Get("http://127.0.0.1:8080/join")
http.Get
like many other go functions return the error so if you have written your code you like:
_, err := http.Get("127.0.0.1:8080/join")
if err != nil{
fmt.Println(err)
}
you would have seen:
Get 127.0.0.1:8080/join: unsupported protocol scheme ""
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论