duankange2433 2017-10-17 10:24
浏览 41
已采纳

如何编写对stdout的HTTP响应?

I am trying to write to stdout the raw HTTP response received from a GET request. I thought httputil.DumpResponse would do what I want but it seems to include mysterious byte counts on "bigger" responses.

For example:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8
Date: Mon, 16 Oct 2017 15:07:53 GMT

1f43
THE ACTUAL BODY CONTENT WHICH IS 8003 BYTES
0

The 1f43 seems to be the length of the response body. Go's http.response talks about trailers, so maybe the 0 is the size of the trailer.

My code is:

    var resp *http.Response
    var err error

    if *isPost {
        resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(*data))
    } else {
        resp, err = http.Get(url)
    }

    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    dump, err := httputil.DumpResponse(resp, true)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", dump)

I have read the code for DumpResponse and TransferWriter but I can't figure out where the 1f43 and 0 come from.

If I make the same request with curl, I don't get the 1f43 and 0 in the response.

Is this the best way to write the raw HTTP response? If so, how can I fix it to avoid these byte counts?

  • 写回答

1条回答 默认 最新

  • dongnuo6310 2017-10-18 19:45
    关注

    You can use interfaces for that,

    The http.Get call returns a pointer to a Response type, which contains a Body, if you check Body interfaces, you can see that the Body implements the io.ReadCloser, which, implements both the Reader and Closer interfaces;

    By understanding these interfaces you can make use of eg: io.Copy

    func Copy(dst Writer, src Reader) (written int64, err error) {...}
    

    As second argument, you could pass the Response Body, which implements the Reader.

    As first argument, Writer, you could both implement your own custom type, and create a func to implement the Writer interface, or, you can also use the built in os.Stdout, which already implements it.

    package main
    
    import (
        "fmt"
        "io"
        "net/http"
        "os"
    )
    
    func main() {
    
        resp, err := http.Get("http://google.com")
    
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(1)
        }
    
        io.Copy(os.Stdout, resp.Body)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。