Soubriquet
Soubriquet

Reputation: 3330

Golang http.Get()

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

Upvotes: 0

Views: 8270

Answers (2)

Nima Ghotbi
Nima Ghotbi

Reputation: 671

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

Upvotes: 2

Thundercat
Thundercat

Reputation: 120931

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

Upvotes: 7

Related Questions