在Golang中将port转换为字符串类型的:port

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

if err := http.ListenAndServe(fmt.Sprintf(":%d", port), handler); err != nil {
        log.Fatal(err)
}

Use strconv.Itoa()

Something like:

p := strconv.Itoa(port)
addr := ":" + p
// or for localhost only
// addr := "localhost:" + p

Then

if err := http.ListenAndServe(addr, nil); err != nil {
    log.Fatal("ListenAndServe: ", err)
}

I'm assuming you're using something like flag.Int to get an int.

Instead of taking port int as an argument, consider taking address string instead, where address can be host[:port] where port is optional.

You can use a function like this to determine if a port was specified:

func hasPort(s string) bool {
    return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
}

(Above is borrowed from /src/pkg/net/http/client.go)

This will work even for IPv6 addresses.

With that function you can do this:

if !hasPort(addr) {
    addr += ":80"
}
log.Fatal(http.ListenAndServe(addr, nil))

If you must convert an int, strconv.Itoa is the way to go. You want to avoid using fmt, as it uses reflection to determine the type, which given the static typing you already know the type.

As far as validating the address itself, the net package, used by http, will emit an error if the address is not in a format understood by net, so you just have to catch the error and do something with it.

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