2013-07-12 05:16 阅读 66


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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    dongli8979 dongli8979 2013-07-12 05:37
    if err := http.ListenAndServe(fmt.Sprintf(":%d", port), handler); err != nil {
    点赞 评论 复制链接分享
  • doumi1944 doumi1944 2013-07-12 05:28

    Use strconv.Itoa()

    Something like:

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


    if err := http.ListenAndServe(addr, nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    点赞 评论 复制链接分享
  • dongtan6695 dongtan6695 2013-07-12 17:49

    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.

    点赞 评论 复制链接分享
  • dplece1882 dplece1882 2014-10-16 18:15

    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:

    点赞 评论 复制链接分享