diff --git a/.gitignore b/.gitignore index a00c64b..33b0950 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ profile*.pdf /pre-commit.sh /TODO.md /playground +/playground/cc /pkg/tag /pkg/nazatime diff --git a/pkg/nazahttp/http.go b/pkg/nazahttp/http.go new file mode 100644 index 0000000..11bcf24 --- /dev/null +++ b/pkg/nazahttp/http.go @@ -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) +} diff --git a/pkg/nazahttp/http_test.go b/pkg/nazahttp/http_test.go new file mode 100644 index 0000000..19ddd6b --- /dev/null +++ b/pkg/nazahttp/http_test.go @@ -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) +}