go - 类型 *url.URL 没有字段或方法 ParseRequestURI

标签 go

这是我的代码:

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/

相关文章:

go - 用于 GO 应用程序和 mongodb 的干净和通用的项目结构

html - Golang 模板中的嵌套范围

arrays - 如何使用for循环遍历2D数组

curl - NTLM 和 Golang

regex - 使用 Regex golang 查找所有字符串匹配项

go - 在 Cobra 命令行工具中,如何为不同的标志使用相同的变量?

string - Golang将字符串转换为io.Writer?

google-app-engine - Go - 找不到包 "appengine"

ubuntu - "go get collidermain"时 golang.org/x/net/websocket 出错 --- 在 Ubuntu 14.04 服务器上部署 AppRTC

Golang 如何检查 struct field int 是否设置?