有没有内置的方法可以获取不包含查询字符串的URL?

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

Is there a built-in method to get a URL minus the query string?

问题

有没有内置的方法可以获取URL的部分,而不包括查询字符串?比如从http://example.com/?search=test中获取http://example.com/

通过URL结构的字段组装(甚至可以通过问号字符进行分割)很容易实现,所以我不需要示例代码。这只是一个简单的问题,我想知道源代码/文档中是否有相关内容。谢谢!

英文:

Is there a built-in method to get the portion of a URL minus the query string? Like http://example.com/ from http://example.com/?search=test?

It's trivial to assemble from the fields of the URL struct (or even by splitting on the question mark char) so I'm not looking for sample code. This is just a simple question to see if it's there in the source/docs and I'm missing it. Thanks!

答案1

得分: 2

没有。没有适用于您的确切用例的便利函数。

但是,您可以使用net/url包来创建一个:

package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	result, err := url.Parse("http://example.com/?search=test?")
	if err != nil {
		log.Fatal("Invalid url", err)
	}
	fmt.Println(result.Scheme+"://"+result.Host+result.Path)
	// or
	result.RawQuery = ""

	fmt.Println(result)
}
英文:

No. There is no convenience function for your exact use case.

but, you can use the net/url package to create one:

http://play.golang.org/p/Kk3EPBXMsm

package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	result, err := url.Parse("http://example.com/?search=test?")
	if err != nil {
		log.Fatal("Invalid url", err)
	}
	fmt.Println(result.Scheme+"://"+result.Host+result.Path)
	// or
	result.RawQuery = ""
	
	fmt.Println(result)
}

答案2

得分: 0

对于其他正在寻找这些信息的人来说,正确的答案是否定的,没有内置的方法可以处理这个问题,可以按照我在问题中描述的方式处理,或者如上所示进行处理。

英文:

For others who are searching for this information, the correct answer is no, there isn't a built-in method for this, and it can be handled as I described in my question, or as demonstrated above.

huangapple
  • 本文由 发表于 2014年8月27日 01:47:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/25512085.html
匿名

发表评论

匿名网友

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

确定