Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with REST HTTPS Server

Tags:

go

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?

like image 853
Jose V. Espi Avatar asked Mar 27 '26 16:03

Jose V. Espi


1 Answers

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"))
}
like image 138
nemo Avatar answered Mar 29 '26 11:03

nemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!