Accept-Encoding == “gzip”, 读resp.Body时会自动ungzip吗?

372 views
Skip to first unread message

guagua

unread,
Nov 11, 2013, 9:30:00 PM11/11/13
to golang...@googlegroups.com
package main


import (
 "fmt"
 "io"
 "net/http"
 "os"
)


func main() {
 req, err := http.NewRequest("GET", "http://www.baidu.com/", nil)
 if err != nil {
 fmt.Println(err)
 return
 }
 req.Header.Add("Accept-Encoding", "gzip,deflate,sdch")


 client := &http.Client{}
 resp, err := client.Do(req)
 if err != nil {
 fmt.Println(err)
 return
 }
 defer resp.Body.Close()


 io.Copy(os.Stdout, resp.Body)
 fmt.Println(resp.Header.Get("Content-Encoding")) //确实是gzip
}

Transport.DisableCompression的解释,应该会自动ungzip的,但是事实上输出的是压缩的内容。

yuchen12

unread,
Nov 11, 2013, 9:55:22 PM11/11/13
to golang...@googlegroups.com
    // DisableCompression, if true, prevents the Transport from
    // requesting compression with an "Accept-Encoding: gzip"
    // request header when the Request contains no existing
    // Accept-Encoding value. If the Transport requests gzip on
    // its own and gets a gzipped response, it's transparently
    // decoded in the Response.Body. However, if the user
    // explicitly requested gzip it is not automatically
    // uncompressed.

�����ʽָ����Accept-Encoding�Ͳ����Զ���ѹ���ˡ�


On 11/12/2013 10:30 AM, guagua wrote:
package main


import (
 "fmt"
 "io"
 "net/http"
 "os"
)


func main() {
 req, err := http.NewRequest("GET", "http://www.baidu.com/", nil)
 if err != nil {
 fmt.Println(err)
 return
 }
 req.Header.Add("Accept-Encoding", "gzip,deflate,sdch")


 client := &http.Client{}
 resp, err := client.Do(req)
 if err != nil {
 fmt.Println(err)
 return
 }
 defer resp.Body.Close()


 io.Copy(os.Stdout, resp.Body)
 fmt.Println(resp.Header.Get("Content-Encoding")) //ȷʵ��gzip
}

��Transport.DisableCompression�Ľ��ͣ�Ӧ �û��Զ�ungzip�ģ�������ʵ���������ѹ�������ݡ�
--
--
����: http://golang-china.org/
IRC: irc.freenode.net #golang-china
@golangchina
---
���յ����ʼ�����Ϊ������ Google ������̳�ġ�Golang-China����̳��
Ҫ�˶�����̳��ֹͣ���մ���̳�ĵ����ʼ����뷢�͵����ʼ��� golang-china...@googlegroups.com��
Ҫ�������ϲ鿴�����ۣ������ https://groups.google.com /d/msgid/golang-china/587bd187-1049-49c3-ba04- c67a91ea377f%40googlegroups.com��
Ҫ�鿴���ѡ������ https://groups.google.com /groups/opt_out��

guagua

unread,
Nov 11, 2013, 10:15:22 PM11/11/13
to golang...@googlegroups.com
我看到你的是乱码,但是baidu首页也不可能是gzip文件

guagua

unread,
Nov 11, 2013, 10:57:57 PM11/11/13
to golang...@googlegroups.com
确实不能显示指定Accept-Encoding,下面是源码:

if !pc.t.DisableCompression && req.Header.Get("Accept-Encoding") == "" && req.Method != "HEAD" {
// Request gzip only, not deflate. Deflate is ambiguous and
// not as universally supported anyway.
//
// Note that we don't request this for HEAD requests,
// due to a bug in nginx:
requestedGzip = true
req.extraHeaders().Set("Accept-Encoding", "gzip")
}

Reply all
Reply to author
Forward
0 new messages