REST HTTPS服务器出现错误

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

Error with REST HTTPS Server

问题

我正在尝试在Golang中创建一个带有TLS的REST服务器,但程序无法正常工作:

http.Handle("/", gorest.Handle())
err = http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)

如果我使用非root用户运行它,会出现listen tcp 127.0.0.1:443: permission denied的错误。使用root用户运行时不会显示之前的错误消息,但在调用ListenAndServeTLS时执行会被阻塞。操作系统是Linux x86_64。有什么想法吗?

英文:

I'm trying to create a REST Server with TLS in Golang, but the program is not working:

http.Handle("/", gorest.Handle())
err = http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)

If I run it with a non-root user I get listen tcp 127.0.0.1:443: permission denied. Running it with root user does not show previous message but execution blocks when invoking
ListenAndServeTLS. OS used is Linux x86_64. Any ideas?

答案1

得分: 10

权限

端口号小于等于1024的是特权端口。除非你是root用户或者有明确的权限使用它们,否则你不能使用它们。参见这个答案进行解释,或者参考维基百科或其他你信任的来源。

参见这个答案以了解如何在不给予超级用户权限的情况下允许你的应用程序打开这些端口(这是一个不好的主意)。以下是关键步骤:

sudo setcap 'cap_net_bind_service=+ep' /opt/yourGoBinary

阻塞

ListenAndServe及其TLS版本ListeAndServeTLS是阻塞的。

当访问/时,由gorest.Handle()返回的HTTP处理程序是并发执行的。如果你想要同时运行其他代码,请在运行ListeAndServe之前启动一个goroutine或实现不同的HTTP处理程序。

以下是使用goroutine的示例:

func printStuff() {
    time.Sleep(1 * time.Second)
    fmt.Println("foo")
}

func main() {
    go printStuff()
    log.Fatal(http.ListeAndServe(":80"))
}
英文:

Permissions

Ports <= 1024 are privileged ports. You can't use them unless you're root or have the explicit
permission to use them. See this answer for an explanation or wikipedia or something
you trust more.

See this answer for a solution to allow your application to open these ports without
giving them superuser permissions (which is a bad idea). Money Quote:

sudo setcap &#39;cap_net_bind_service=+ep&#39; /opt/yourGoBinary

Blocking

ListenAndServe and its TLS counterpart ListeAndServeTLS are blocking.

The http handler returned by gorest.Handle() is executed concurrently when / is accessed.
If you want to have other code running concurrently, start a goroutine before running ListeAndServe
or implement different http handlers.

Example using goroutines:

func printStuff() {
    time.Sleep(1 * time.Second)
    fmt.Println(&quot;foo&quot;)
}

func main() {
    go printSTuff()
    log.Fatal(http.ListeAndServe(&quot;:80&quot;))
}

huangapple
  • 本文由 发表于 2013年10月10日 01:57:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/19279294.html
匿名

发表评论

匿名网友

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

确定