How to get the URL in Go

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

How to get the URL in Go

问题

我尝试查找,但找不到已经回答的问题。

如何在Go中获取URL的主机部分?

例如,

如果用户在地址栏中输入http://localhost:8080,我想从URL中提取"localhost"。

英文:

I tried looking it up, but couldn't find an already answered question.

How do I get the host part of the URL in Go?

For eg.

if the user enters http://localhost:8080 in the address bar, I wanted to extract "localhost" from the URL.

答案1

得分: 3

如果你想从*http.Request中提取主机名,可以按照以下方式操作:

    host := r.Host // 这是你的主机名(如果指定了端口,也会包括在内)
}

如果你只想访问主机名部分而不包括端口部分,可以按照以下方式操作:

    host, port, _ := net.SplitHostPort(r.Host)
}

要使最后一个示例正常工作,你还需要导入net包。

Go语言有很好的文档,我也建议你查看一下:net/http

英文:

If you are talking about extracting the host from a *http.Request you can do the following:

    host := r.Host // This is your host (and will include port if specified)
}

If you just want to access the host part without the port part you can do the following:

    host, port, _ := net.SplitHostPort(r.Host)
}

For the last one to work you also have to import net

Go has wonderful documentation, I would also recommend taking a look at that: net/http

答案2

得分: 1

Go语言内置了一个可以为您完成此操作的库。

package main
import "fmt"
import "net"
import "net/url"
func main() {
    s := "http://localhost:8080"

    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    host, _, _ := net.SplitHostPort(u.Host)
    fmt.Println(host)
}

https://golang.org/pkg/net/url/

英文:

Go has built in library that can do it for you.

package main
import "fmt"
import "net"
import "net/url"
func main() {
    s := "http://localhost:8080"

    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    host, _, _ := net.SplitHostPort(u.Host)
    fmt.Println(host)
}

https://golang.org/pkg/net/url/#

huangapple
  • 本文由 发表于 2017年9月5日 23:02:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/46058142.html
匿名

发表评论

匿名网友

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

确定