mirror of https://github.com/q191201771/naza
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
5 years ago
|
// Copyright 2020, Chef. All rights reserved.
|
||
|
// https://github.com/q191201771/naza
|
||
|
//
|
||
|
// Use of this source code is governed by a MIT-style license
|
||
|
// that can be found in the License file.
|
||
|
//
|
||
|
// Author: Chef (191201771@qq.com)
|
||
|
|
||
5 years ago
|
package nazahttp
|
||
|
|
||
|
import (
|
||
|
"io"
|
||
5 years ago
|
"io/ioutil"
|
||
5 years ago
|
"net/http"
|
||
|
"os"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
5 years ago
|
// 获取http文件保存至字节切片
|
||
|
func GetHTTPFile(url string, timeoutMSec int) ([]byte, error) {
|
||
5 years ago
|
var c http.Client
|
||
|
if timeoutMSec > 0 {
|
||
|
c.Timeout = time.Duration(timeoutMSec) * time.Millisecond
|
||
|
}
|
||
|
resp, err := c.Get(url)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
defer resp.Body.Close()
|
||
|
|
||
|
content, err := ioutil.ReadAll(resp.Body)
|
||
|
return content, err
|
||
|
}
|
||
|
|
||
|
// 获取http文件保存至本地
|
||
5 years ago
|
func DownloadHTTPFile(url string, saveTo string, timeoutMSec int) (int64, error) {
|
||
5 years ago
|
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)
|
||
|
}
|