英文:
golang - HTTP client always escaped the URL
问题
有没有办法让golang的HTTP客户端不对请求的URL进行转义呢?例如,对于URL "/test(a)" 的请求,会被转义为 "/test%28a%29"。我正在运行来自https://github.com/cmpxchg16/gobench的代码。
英文:
Is there anyway for golang HTTP client,not to escape the requested URL.<br>
For example, a request for URL "/test(a)", gets escaped to "/test%28a%29".<br>
I'm running the code from https://github.com/cmpxchg16/gobench<br>
答案1
得分: 9
你可以设置一个不透明的URL。
假设你想要的URL指向http://example.com/test(a)
,你可以这样做:
req.NewRequest("GET", "http://example.com/test(a)", nil)
req.URL = &url.URL{
Scheme: "http",
Host: "example.com",
Opaque: "//example.com/test(a)",
}
client.Do(req)
示例:http://play.golang.org/p/09V67Hbo6H
文档:http://golang.org/pkg/net/url/#URL
英文:
You can set an opaque url.
Assuming you want the url to point to http://example.com/test(a)
you would want to do:
req.NewRequest("GET", "http://example.com/test(a)", nil)
req.URL = &url.URL{
Scheme: "http",
Host: "example.com",
Opaque: "//example.com/test(a)",
}
client.Do(req)
Example: http://play.golang.org/p/09V67Hbo6H
Documentation: http://golang.org/pkg/net/url/#URL
答案2
得分: 1
这似乎是URL包中的一个错误:
https://code.google.com/p/go/issues/detail?id=6784
和 https://code.google.com/p/go/issues/detail?id=5684
答案3
得分: 1
你需要将Unescaped Path设置为URL Path,并将Encoded Path设置为RawURL,否则会出现双重转义,例如:
package main
import (
"fmt"
"net/url"
)
func main() {
doubleEncodedURL := &url.URL{
Scheme: "http",
Host: "example.com",
Path: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa%2BIFVla4ZdfRiMzfh%2FEGs7f/events",
}
rawEncodedURL := &url.URL{
Scheme: "http",
Host: "example.com",
Path: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa+IFVla4ZdfRiMzfh/EGs7f/events",
RawPath: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa%2BIFVla4ZdfRiMzfh%2FEGs7f/events",
}
fmt.Printf("doubleEncodedURL is : %s\n", doubleEncodedURL)
fmt.Printf("rawEncodedURL is : %s\n", rawEncodedURL)
}
Playground链接:https://play.golang.org/p/rOrVzW8ZJCQ
英文:
You need to set Unescaped Path to URL Path and Encoded Path to RawURL or else it will double escape e.g.
package main
import (
"fmt"
"net/url"
)
func main() {
doubleEncodedURL := &url.URL{
Scheme: "http",
Host: "example.com",
Path: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa%2BIFVla4ZdfRiMzfh%2FEGs7f/events",
}
rawEncodedURL := &url.URL{
Scheme: "http",
Host: "example.com",
Path: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa+IFVla4ZdfRiMzfh/EGs7f/events",
RawPath: "/id/EbnfwIoiiXbtr6Ec44sfedeEsjrf0RcXkJneYukTXa%2BIFVla4ZdfRiMzfh%2FEGs7f/events",
}
fmt.Printf("doubleEncodedURL is : %s\n", doubleEncodedURL)
fmt.Printf("rawEncodedURL is : %s\n", rawEncodedURL)
}
Playground link: https://play.golang.org/p/rOrVzW8ZJCQ
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论