From c16b7be9ac333ce0db2cb755f5e05d4e6d4c823d Mon Sep 17 00:00:00 2001 From: smallfish Date: Mon, 18 Aug 2014 21:29:45 +0800 Subject: [PATCH] rollback the ToFile func implement, and add testcase --- httplib/httplib.go | 8 ++++++-- httplib/httplib_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/httplib/httplib.go b/httplib/httplib.go index 18e4caf3..1c0d5544 100644 --- a/httplib/httplib.go +++ b/httplib/httplib.go @@ -421,11 +421,15 @@ func (b *BeegoHttpRequest) ToFile(filename string) error { } defer f.Close() - data, err := b.Bytes() + resp, err := b.getResponse() if err != nil { return err } - _, err = f.Write(data) + if resp.Body == nil { + return nil + } + defer resp.Body.Close() + _, err = io.Copy(f, resp.Body) return err } diff --git a/httplib/httplib_test.go b/httplib/httplib_test.go index b352bd4a..2d49d875 100644 --- a/httplib/httplib_test.go +++ b/httplib/httplib_test.go @@ -15,6 +15,8 @@ package httplib import ( + "io/ioutil" + "os" "strings" "testing" ) @@ -41,6 +43,10 @@ func TestGet(t *testing.T) { t.Fatal(err) } t.Log(s) + + if string(b) != s { + t.Fatal("request data not match") + } } func TestSimplePost(t *testing.T) { @@ -171,3 +177,17 @@ func TestToJson(t *testing.T) { t.Fatal("response is not valid ip") } } + +func TestToFile(t *testing.T) { + f := "beego_testfile" + req := Get("http://httpbin.org/ip") + err := req.ToFile(f) + if err != nil { + t.Fatal(err) + } + defer os.Remove(f) + b, err := ioutil.ReadFile(f) + if n := strings.Index(string(b), "origin"); n == -1 { + t.Fatal(err) + } +}