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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试