这是我的代码:
director := func(req *http.Request) {
fmt.Println(req.URL)
regex, _ := regexp.Compile(`^/([a-zA-Z0-9_-]+)/(\S+)$`)
match := regex.FindStringSubmatch(req.URL.Path)
bucket, filename := match[1], match[2]
method := "GET"
expires := time.Now().Add(time.Second * 60)
signedUrl, err := storage.SignedURL(bucket, filename, &storage.SignedURLOptions{
GoogleAccessID: user.GoogleAccessID,
PrivateKey: []byte(user.PrivateKey),
Method: method,
Expires: expires,
})
if err != nil {
fmt.Println("Error " + err.Error())
}
fmt.Println(signedUrl)
req.URL.ParseRequestURI(signedUrl)
}
我想使用 ParseRequestURI 方法将 signedUrl 解析为 req.URL https://golang.org/pkg/net/url/#ParseRequestURI
但是编译的时候报错:
req.URL.ParseRequestURI 未定义(类型 *url.URL 没有字段或方法 ParseRequestURI)
所以我尝试了 req.URL.Parse
并且它有效。
https://golang.org/pkg/net/url/#Parse
这两个功能在文档中彼此接近。我找不到它们之间的任何显着差异。所以我不知道为什么一个有效而另一个无效。
如何使 ParseRequestURI
工作?为什么一个有效而另一个无效?
最佳答案
正如您提到的,以下函数调用不起作用:
req.URL.ParseRequestURI(signedUrl)
因为:
func ParseRequestURI(rawurl string) (*URL, error)
在net/url
包下定义为包级函数(reference) ,因此不能使用 type
调用。虽然正确的调用方式如下:
url.ParseRequestURI(signedUrl) // Here 'url' is from package name i.e. 'net/url'
另一方面,正如您提到的,您可以成功调用 req.URL.Parse
,因为 Parse
是在 package
中定义的级别,即在“net/url”(reference)以及 type
级别的类型 *URL
(reference) .
Parse
at package net/url
定义为:
func Parse(rawurl string) (*URL, error)
类型Parse parses rawurl into a URL structure.
The rawurl may be relative (a path, without a host) or absolute (starting with a scheme). Trying to parse a hostname and path without a scheme is invalid but may not necessarily return an error, due to parsing ambiguities.
*URL
的 Parse
定义为:
func (u *URL) Parse(ref string) (*URL, error)
Parse parses a URL in the context of the receiver. The provided URL may be relative or absolute. Parse returns nil, err on parse failure, otherwise its return value is the same as ResolveReference.
希望对你有帮助
关于go - 类型 *url.URL 没有字段或方法 ParseRequestURI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960802/