p_mcp
p_mcp

Reputation: 2791

Golang port blocking (?) using http.ListenAndServe

I have a simple golang program which listens for activity on a port before executing a function called testFunc

func main() {
    http.HandleFunc("/test", testFunc)
    http.ListenAndServe(":1337", nil)
}

When I build this program, run it and go to http://localhost:1337/test, it works fine.

When I terminate the program and try and run it again, the program instantly terminates showing no error output.

When I then change the port to 1338 for example, it works the first time, then fails each time after. Any ideas?

Upvotes: 0

Views: 3304

Answers (2)

maverickames
maverickames

Reputation: 191

The port is most likely in use. Catching the error will give you more details.

if err := http.ListenAndServe(":1337", nil);err != nil {
        log.Fatal("ListenAndServe: ", err)
}

Upvotes: 2

p_mcp
p_mcp

Reputation: 2791

Ok turns out the error was my silly mistake. I have today switched from using a PC to Mac and didn't realise that Ctrl+C killed the current command instead of Ctrl+z which simply returns to shell... Therefore the processes were still running and blocking each other

Upvotes: 1

Related Questions