Golang port blocking (?) using http.ListenAndServe

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

Golang port blocking (?) using http.ListenAndServe

问题

我有一个简单的golang程序,它监听一个端口上的活动,然后执行一个名为testFunc的函数。

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

当我构建并运行这个程序,并访问http://localhost:1337/test时,它能正常工作。

但是当我终止程序并尝试再次运行时,程序立即终止,没有显示任何错误输出。

当我将端口更改为例如1338时,它第一次能正常工作,但之后每次都失败。有什么想法吗?

英文:

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?

答案1

得分: 2

端口很可能正在使用中。捕获错误将提供更多详细信息。

如果 err := http.ListenAndServe(":1337", nil);err != nil {
		log.Fatal("ListenAndServe: ", err)
}
英文:

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

答案2

得分: 1

好的,以下是翻译好的内容:

好吧,事实证明错误是我愚蠢的错误。我今天从使用PC切换到Mac,没有意识到Ctrl+C是终止当前命令,而不是Ctrl+z,后者只是返回到shell...因此进程仍在运行并相互阻塞。

英文:

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

huangapple
  • 本文由 发表于 2015年3月27日 03:05:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/29286860.html
匿名

发表评论

匿名网友

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

确定