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

huangapple go评论74阅读模式
英文:

Convert port to :port of type string in Golang

问题

如何将用户输入的端口转换为类型为“:port”的字符串(即,在其前面应该有一个“:”,并且应该转换为字符串)。输出必须提供给http.ListenAndServe()。

英文:

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

答案1

得分: 4

你可以(应该?)使用net.JoinHostPort(host, port string)

使用strconv.Itoaport转换为字符串。

它还可以处理主机部分包含冒号的情况:“host:port”。直接将其传递给ListenAndServe

以下是一些示例代码:

host := ""
port := 80
str := net.JoinHostPort(host, strconv.Itoa(port))
fmt.Printf("host:port = '%s'", str)
// 可以直接传递给:
// http.ListenAndServe(str, nil)

以上代码可以在playground上运行:https://play.golang.org/p/AL3obKjwcjZ

英文:

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

答案2

得分: 3

使用strconv.Itoa()

类似于:

p := strconv.Itoa(port)
addr := ":" + p
// 或者仅限于本地主机
// addr := "localhost:" + p

然后

if err := http.ListenAndServe(addr, nil); err != nil {
    log.Fatal("ListenAndServe: ", 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)
}

答案3

得分: 3

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

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

huangapple
  • 本文由 发表于 2013年7月12日 13:16:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/17607843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定