2017-03-08 50 views
-2

我想寫一個基本的http服務器示例。我可以捲曲localhost:8080,但無法通過客戶端腳本與http.Get("127.0.0.1:8080")聯繫服務器。我究竟做錯了什麼?Golang http.Get()

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") 
+0

「我[...]不能聯繫服務器」是不是一個有用的描述交流你所面臨的問題。順便說一句:捕獲和處理來自http.Get的錯誤將在這裏提供信息。 – Volker

回答

5

嘗試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) 
} 
0

您have't指定的方案,儘量http.Get("http://127.0.0.1:8080/join")

http.Get像許多其他的功能去返回錯誤,所以如果你寫你的代碼,如:

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