doukang8949 2016-09-01 11:42
浏览 533
已采纳

为什么url.Parse不填充URL.RawPath?

While with similar input, URL.RawQuery seems to be properly populated.

Playground

u, err := url.Parse("https://example.com/foo%2fbar")
if err != nil {
    log.Fatal(err)
}
fmt.Println(u.Path)
fmt.Println(u.RawPath)
fmt.Println(u.String(), "
")

u, err = url.Parse("https://example.com/foo%25fbar?q=morefoo%25bar")
if err != nil {
    log.Fatal(err)
}
fmt.Println(u.Path)
fmt.Println(u.RawPath)
fmt.Println(u.RawQuery)
fmt.Println(u.String())
  • 写回答

2条回答 默认 最新

  • dongxi5505 2016-09-01 12:16
    关注

    Note that URL.RawPath is not the raw (escaped) path. It may be, but not always. It's just a hint. Its doc says:

    RawPath    string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
    

    So when you need the escaped path, always use URL.EscapedPath() and don't rely on the URL.RawPath field. Doc of URL.EscapedPath() says:

    EscapedPath returns u.RawPath when it is a valid escaping of u.Path.

    This is your case. A raw path is invalid if it contains bytes that need escaping during URL encoding. Your path is such an example because it contains %25 which is the URL escaped text of the percent symbol itself '%', and percent symbols need to be escaped if part of URL paths.

    Your first example contained %2f which is the URL escaped text of the slash'/' which if present in a path does not need to be escaped ('/' is a valid character in paths and is treated as a separator).

    See this example:

    u, err = url.Parse("https://example.com/foo%25fbar?q=morefoo%25bar")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Path:       ", u.Path)
    fmt.Println("RawPath:    ", u.RawPath)
    fmt.Println("EscapedPath:", u.EscapedPath())
    fmt.Println("RawQuery:   ", u.RawQuery)
    fmt.Println("String:     ", u.String())
    

    Output (try it on the Go Playground):

    Path:        /foo%fbar
    RawPath:     
    EscapedPath: /foo%25fbar
    RawQuery:    q=morefoo%25bar
    String:      https://example.com/foo%25fbar?q=morefoo%25bar
    

    RawPath is the empty string (because "/foo%25fbar" is an invalid escaped path), but EscapedPath() returns you the original escaped path.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档