mirror of
https://github.com/astaxie/beego.git
synced 2024-11-06 01:50:55 +00:00
Merge pull request #3900 from aixiaoxiang/develop
httplib:fixes network request failed to create an invalid file and automatically created file directory
This commit is contained in:
commit
1b7f5ba2c4
@ -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 {
|
||||
|
@ -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")
|
||||
|
Loading…
Reference in New Issue
Block a user