Golang的HTTP HelloWorld不会阻塞。

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

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 接口的对象。如果调用不会阻塞,那么肯定意味着发生了某种错误。最常见的错误有:

  • 已经有另一个进程在监听该端口
  • 您的用户没有权限在端口 80800.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, or 0.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

huangapple
  • 本文由 发表于 2014年8月4日 23:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/25121810.html
匿名

发表评论

匿名网友

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

确定