英文:
golang http helloworld doesn't block
问题
我的代码与gowiki中的代码完全相同。
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
然而,当我构建并运行这个程序后,它立即退出而不会阻塞,所以当我尝试从Chrome访问http://localhost:8080/monkey
时,我得不到任何响应。
环境:Ubuntu 14(在Windows 7上的VirtualBox中)
为什么会这样?
英文:
My code is just the same as in gowiki
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
However, after I build and run this program, it exit immediately without blocking so that I get no response when I try to access http://localhost:8080/monkey
from Chrome.
Environment: Ubuntu 14(in VirtualBox on Windows7)
Why?
答案1
得分: 20
检查从ListenAndServe
返回的错误
func main() {
http.HandleFunc("/", handler)
fmt.Println(http.ListenAndServe(":8080", nil))
}
请注意,这是一个Go语言代码示例,用于设置HTTP服务器并监听端口8080。ListenAndServe
函数返回一个错误,你可以通过检查该错误来查看服务器是否成功启动。
英文:
Check the error returned from ListenAndServe
func main() {
http.HandleFunc("/", handler)
fmt.Println(http.ListenAndServe(":8080", nil))
}
答案2
得分: 5
http.ListenAndServe
函数返回一个符合 error
接口的对象。如果调用不会阻塞,那么肯定意味着发生了某种错误。最常见的错误有:
- 已经有另一个进程在监听该端口
- 您的用户没有权限在端口
8080
或0.0.0.0
接口上绑定套接字
英文:
http.ListenAndServe
function returns an object that conforms error
interface. If the call does not block, it definitely means that some kind of error has happened. The most popular are:
- there is already another process listening that port
- your user has no right to bind socket on port
8080
, or0.0.0.0
interface
答案3
得分: 1
在我的情况下,出现了一个“权限被拒绝”的错误。使用sudo
命令可以解决问题。
sudo go run filename.go
或者
sudo filename
英文:
In my case, it was a permission denied
error. Using sudo
worked like a charm.
sudo go run filename.go
or
sudo filename
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论