1
我使用net/http
库在“开始”作出HTTP GET
请求。在回应中,我得到了12个标题。但是,当我通过邮递员运行完全相同的查询时,我得到了16个标题。其中一个遗漏的是“内容编码”。我明白这一定是CORS问题。转到:检测gzip编码手动解压缩响应,但“内容编码”标头丢失
但是因为我没有在我的请求中设置标头Accept-Encoding: gzip
,而且我仍然得到gzip编码的响应,所以Go运输不是automatically decompressing the response for me。所以,我需要能够手动检测编码,然后解压缩它。但是,我无法检测到响应中是否缺少'Content-Encoding'标头。
这里是我的代码,我尝试这样做:
func calcDistanceAndDurationWithUberApi(originLat float64, originLon float64, destinationLat float64, destinationLon float64) (float64, float64, error) {
endpoint := "https://api.uber.com/v1.2/estimates/price"
parameters := fmt.Sprintf("?start_latitude=%v&start_longitude=%v&end_latitude=%v&end_longitude=%v", originLat, originLon, destinationLat, destinationLon)
req, err := http.NewRequest("GET", endpoint + parameters, nil)
if err != nil {
return 0, 0, err
}
req.Header.Add("Authorization", "Token " + getUberApiKey())
req.Header.Add("Accept-Language", "en_US")
req.Header.Add("Content-Type", "application/json")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return 0, 0, err
}
if resp.StatusCode != 200 {
return 0, 0, errors.NotFound("Response: %v", resp.StatusCode)
}
defer resp.Body.Close()
pretty.Println("- REQUEST: ")
pretty.Println(req)
// Check if server sent gzipped response. Decompress if yes.
var respReader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
fmt.Println("Content-Encoding is gzip")
respReader, err = gzip.NewReader(resp.Body)
defer respReader.Close()
default:
fmt.Println("Content-Encoding is Not gzip")
respReader = resp.Body
}
pretty.Println("- RESPONSE HEADER: ")
pretty.Println(resp.Header)
pretty.Println("- RESPONSE BODY: ")
pretty.Println(respReader)
return 0, 0, nil
}
响应状态是 '200 OK'。这里是输出(响应):我给到超级API的顽固和加入另一个请求头,req.Header.Add("Accept-Encoding", "gzip")
- RESPONSE HEADER:
http.Header{
"Content-Language": {"en"},
"Cache-Control": {"max-age=0"},
"X-Uber-App": {"uberex-nonsandbox", "optimus"},
"Strict-Transport-Security": {"max-age=604800", "max-age=2592000"},
"X-Content-Type-Options": {"nosniff"},
"Date": {"Fri, 19 May 2017 07:52:17 GMT"},
"Content-Geo-System": {"wgs-84"},
"Connection": {"keep-alive"},
"X-Frame-Options": {"SAMEORIGIN"},
"X-Xss-Protection": {"1; mode=block"},
"Server": {"nginx"},
"Content-Type": {"application/json"},
}
- RESPONSE BODY:
&http.gzipReader{
body: &http.bodyEOFSignal{
body: &http.body{
src: &internal.chunkedReader{
r: &bufio.Reader{
buf: {0x48, 0x54, .......... }
这可能是尤伯杯的API是足够聪明,只包括Content-Encoding头,如果请求者接受gzip的,但实际上没有足够聪明*不gzip压缩的响应*当他们不接受的gzip。如果是这样的话,这对于优步来说绝对是一个缺陷。 – Adrian
但是在同一时间,他们固执地给我gzip-ped回应,不管我是否要求他们 –