How do you convert a port inputted as a int by the user to a string of type ":port" (ie, it should have a ':' in front of it and should be converted to string). The output has to be feed to http.ListenAndServe().
You could (ought to?) use net.JoinHostPort(host, port string)
.
Convert port
to a string with strconv.Itoa
.
It'll also handle the case where the host part contains a colon: "host:port". Feed that directly to ListenAndServe
.
Here is some sample code:
host := ""
port := 80
str := net.JoinHostPort(host, strconv.Itoa(port))
fmt.Printf("host:port = '%s'", str)
// Can be fed directly to:
// http.ListenAndServe(str, nil)
The above can be run on a playground: https://play.golang.org/p/AL3obKjwcjZ
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), handler); err != nil {
log.Fatal(err)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With