Golang的http.Get()函数

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

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 ""

huangapple
  • 本文由 发表于 2017年3月9日 02:44:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/42679436.html
匿名

发表评论

匿名网友

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

确定