英文:
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 'cap_net_bind_service=+ep' /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("foo")
}
func main() {
go printSTuff()
log.Fatal(http.ListeAndServe(":80"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论