57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package callback
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
|
|
"lone-services/pkg/utils"
|
|
)
|
|
|
|
func BuildDownloadURL(object string) (string, error) {
|
|
endpoint := utils.GetConfigString("oss.internalEndpoint")
|
|
if endpoint == utils.StringEmpty {
|
|
endpoint = utils.GetConfigString("oss.endpoint")
|
|
}
|
|
if endpoint == utils.StringEmpty {
|
|
return utils.StringEmpty, fmt.Errorf("oss endpoint empty")
|
|
}
|
|
return url.JoinPath(endpoint, object)
|
|
}
|
|
|
|
func DownloadFile(fileURL, destPath string) error {
|
|
resp, err := http.Get(fileURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("http status %d", resp.StatusCode)
|
|
}
|
|
|
|
tmpPath := destPath + ".tmp"
|
|
out, err := os.Create(tmpPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, copyErr := io.Copy(out, resp.Body)
|
|
closeErr := out.Close()
|
|
if copyErr != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return copyErr
|
|
}
|
|
if closeErr != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return closeErr
|
|
}
|
|
if err = os.Rename(tmpPath, destPath); err != nil {
|
|
_ = os.Remove(tmpPath)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|