0

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
  • "I [...] can't contact the server" is not a helpful description of what actual problem you are facing. BTW: capturing and handling the error from http.Get would be informative here. Commented Mar 8, 2017 at 18:57

2 Answers 2

7

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

hey, say if i dont want to use err in my code how can i replace resp, err := http.Get("http://127.0.0.1:8080/join") with something like response_struct := http.Get("http://127.0.0.1:8080/join") ?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.