英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论