[feat] new pkg/nazahttp

pull/2/head
q191201771 5 years ago
parent 607fc70f30
commit 8128b4db87

1
.gitignore vendored

@ -11,6 +11,7 @@ profile*.pdf
/pre-commit.sh /pre-commit.sh
/TODO.md /TODO.md
/playground /playground
/playground/cc
/pkg/tag /pkg/tag
/pkg/nazatime /pkg/nazatime

@ -0,0 +1,29 @@
package nazahttp
import (
"io"
"net/http"
"os"
"time"
)
// 获取 http 文件保存至本地
func DownloadHttpFile(url string, saveTo string, timeoutMSec int) (int64, error) {
var c http.Client
if timeoutMSec > 0 {
c.Timeout = time.Duration(timeoutMSec) * time.Millisecond
}
resp, err := c.Get(url)
if err != nil {
return -1, err
}
defer resp.Body.Close()
fp, err := os.Create(saveTo)
if err != nil {
return -1, err
}
defer fp.Close()
return io.Copy(fp, resp.Body)
}

@ -0,0 +1,19 @@
package nazahttp_test
import (
"github.com/q191201771/naza/pkg/assert"
"github.com/q191201771/naza/pkg/nazahttp"
"testing"
)
func TestDownloadHttpFile(t *testing.T) {
n, err := nazahttp.DownloadHttpFile("http://pengrl.com", "/tmp/index.html", 10000)
assert.Equal(t, true, n > 0)
assert.Equal(t, nil, err)
n, err = nazahttp.DownloadHttpFile("http://127.0.0.1:12356", "/tmp/index.html", 10000)
assert.IsNotNil(t, err)
n, err = nazahttp.DownloadHttpFile("http://pengrl.com", "/notexist/index.html", 10000)
assert.IsNotNil(t, err)
}
Loading…
Cancel
Save