我的 urlfetch 客户端在部署到 appspot 时工作正常。但是通过代理进行本地测试(dev_appserver.py)有问题。我找不到任何方法来为 urlfetch.Transport 设置代理。
如何在本地测试代理后面的 urlfetch?
最佳答案
http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://developers.google.com/appengine/docs/go/urlfetch/overview
在 GAE dev_appserver.py 上测试 PayPal OAuth 时收到此错误消息(编译后可在生产环境中使用)
const url string = "https://api.sandbox.paypal.com/v1/oauth2/token"
const username string = "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp"
const password string = "EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp"
client := &http.Client{}
req, _ := http.NewRequest("POST", url, strings.NewReader("grant_type=client_credentials"))
req.SetBasicAuth(username, password)
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
如您所见,Go App Engine 破坏了 http.DefaultTransport (GAE_SDK/goroot/src/pkg/appengine_internal/internal.go,第 142 行,GAE 1.7.5)
type failingTransport struct{}
func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
return nil, errors.New("http.DefaultTransport and http.DefaultClient are not available in App Engine. " +
"See https://developers.google.com/appengine/docs/go/urlfetch/overview")
}
func init() {
// http.DefaultTransport doesn't work in production so break it
// explicitly so it fails the same way in both dev and prod
// (and with a useful error message)
http.DefaultTransport = failingTransport{}
}
我用 Go App Engine 1.7.5 解决了这个问题
transport := http.Transport{}
client := &http.Client{
Transport: &transport,
}
req, _ := http.NewRequest("POST", url, strings.NewReader("grant_type=client_credentials"))
req.SetBasicAuth(username, password)
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
关于google-app-engine - 如何通过代理本地测试gae golang urlfetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298264/