go - 检测 gzip 编码以手动解压缩响应,但缺少 'Content-Encoding' header

标签 go http-headers httpresponse content-encoding

我在“Go”中使用 net/http 库来发出 HTTP GET 请求。在响应中,我得到 12 个标题。但是当我通过 postman 运行完全相同的查询时,我得到 16 个标题。缺少的内容之一是“内容编码”。我知道这一定是 CORS问题。

但是由于我没有在我的请求中设置 header Accept-Encoding: gzip,而且我仍然得到 gzip 编码作为响应,Go 传输不是 automatically decompressing the response for me .所以,我需要能够手动检测编码然后解压缩。但是,我无法检测到响应中是否缺少“Content-Encoding” header 。

这是我尝试执行此操作的代码:

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”。这是输出(响应):

- 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, .......... }

最佳答案

我屈服于 uber api 的顽固并添加了另一个请求 header ,req.Header.Add("Accept-Encoding", "gzip")

现在我得到响应 header "Content-Encoding": "gzip",虽然我仍然得到一个无法破译的响应主体,但这超出了这个问题的范围。

关于go - 检测 gzip 编码以手动解压缩响应,但缺少 'Content-Encoding' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44064556/

相关文章:

go - redigo 和 gob 如何检索 gob 数据 slice

戈朗 : command-line-arguments undefined: variable

javascript - PHP - 如何检查请求是否针对 JS worker

http - 最佳实践 : HTTP code for user exceeding usage limitation

android - errorBody() 应为 BEGIN_ARRAY

spring-boot - Spring Boot - Rest Controller 响应两个 JSON 对象

java - JSON 响应以文本形式返回

go - 如何在 Go 中将 "type"用作结构属性?

扫描 AWS S3 时,Python 线程池比 Go 例程更快?

security - 从https页面转到http页面时是否发送HTTP头Referer?