Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert port to :port of type string in Golang

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().

like image 826
Avin D'Silva Avatar asked Jul 12 '13 05:07

Avin D'Silva


Video Answer


2 Answers

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

like image 190
bobc Avatar answered Oct 27 '22 05:10

bobc


if err := http.ListenAndServe(fmt.Sprintf(":%d", port), handler); err != nil {
        log.Fatal(err)
}
like image 40
zzzz Avatar answered Oct 27 '22 03:10

zzzz