From dc5c42e9818de1a60cbf696235c023b84d48d043 Mon Sep 17 00:00:00 2001 From: axx Date: Mon, 30 Dec 2019 11:24:55 +0800 Subject: [PATCH] httplib:fixes network request failed to create an invalid file and automatically created file directory --- httplib/httplib.go | 33 +++++++++++++++++++++++++++------ httplib/httplib_test.go | 14 ++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/httplib/httplib.go b/httplib/httplib.go index 074cf661..9d63505f 100644 --- a/httplib/httplib.go +++ b/httplib/httplib.go @@ -47,9 +47,11 @@ import ( "net/http/httputil" "net/url" "os" + "path" "strings" "sync" "time" + "gopkg.in/yaml.v2" ) @@ -558,12 +560,6 @@ func (b *BeegoHTTPRequest) Bytes() ([]byte, error) { // ToFile saves the body data in response to one file. // it calls Response inner. func (b *BeegoHTTPRequest) ToFile(filename string) error { - f, err := os.Create(filename) - if err != nil { - return err - } - defer f.Close() - resp, err := b.getResponse() if err != nil { return err @@ -572,10 +568,35 @@ func (b *BeegoHTTPRequest) ToFile(filename string) error { return nil } defer resp.Body.Close() + err = pathExistAndMkdir(filename) + if err != nil { + return err + } + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() _, err = io.Copy(f, resp.Body) return err } +//Check that the file directory exists, there is no automatically created +func pathExistAndMkdir(filename string) (err error) { + filename = path.Dir(filename) + _, err = os.Stat(filename) + if err == nil { + return nil + } + if os.IsNotExist(err) { + err = os.MkdirAll(filename, os.ModePerm) + if err == nil { + return nil + } + } + return err +} + // ToJSON returns the map that marshals from the body bytes as json in response . // it calls Response inner. func (b *BeegoHTTPRequest) ToJSON(v interface{}) error { diff --git a/httplib/httplib_test.go b/httplib/httplib_test.go index 7314ae01..dd2a4f1c 100644 --- a/httplib/httplib_test.go +++ b/httplib/httplib_test.go @@ -232,6 +232,20 @@ func TestToFile(t *testing.T) { } } +func TestToFileDir(t *testing.T) { + f := "./files/beego_testfile" + req := Get("http://httpbin.org/ip") + err := req.ToFile(f) + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll("./files") + b, err := ioutil.ReadFile(f) + if n := strings.Index(string(b), "origin"); n == -1 { + t.Fatal(err) + } +} + func TestHeader(t *testing.T) { req := Get("http://httpbin.org/headers") req.Header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36")