[英]How to get the URL in Go
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? 如何在Go中获取URL的主机部分?
For eg. 例如。
if the user enters http://localhost:8080 in the address bar, I wanted to extract "localhost" from the URL. 如果用户在地址栏中输入http:// localhost:8080 ,我想从URL中提取“localhost”。
If you are talking about extracting the host from a *http.Request
you can do the following: 如果您正在讨论从
*http.Request
提取主机,您可以执行以下操作:
func ExampleHander(w http.ResponseWriter, r *http.Request) { 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: 如果您只想访问没有端口部分的主机部件,可以执行以下操作:
func ExampleHandler(w http.ResponseWriter, r *http.Request) { host, port, _ := net.SplitHostPort(r.Host) }
For the last one to work you also have to import net
对于最后一个工作,你还必须导入
net
Go has wonderful documentation, I would also recommend taking a look at that: net/http Go有很棒的文档,我也建议看一下: net / http
Go has built in library that can do it for you. 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/# https://golang.org/pkg/net/url/#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.