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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)