57 lines
991 B
Go
57 lines
991 B
Go
package web
|
|
|
|
import (
|
|
"fmt"
|
|
"image"
|
|
"image/jpeg"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/nfnt/resize"
|
|
)
|
|
|
|
// Download used for downloading file
|
|
var Download = func(srcURL, dest string, maxWidth uint) error {
|
|
if err := createDirectory(dest); err != nil {
|
|
return err
|
|
}
|
|
|
|
var httpClient = &http.Client{
|
|
Timeout: time.Second * 10,
|
|
}
|
|
resp, err := httpClient.Get(srcURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("got HTTP error %s", resp.Status)
|
|
}
|
|
|
|
image, _, err := image.Decode(resp.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if maxWidth != 0 {
|
|
image = resize.Resize(maxWidth, 0, image, resize.Lanczos3)
|
|
}
|
|
|
|
// Create the file
|
|
file, err := os.Create(dest)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
return jpeg.Encode(file, image, nil)
|
|
}
|
|
|
|
// createDirectory creates the destination directory
|
|
func createDirectory(dest string) error {
|
|
return os.MkdirAll(path.Dir(dest), os.ModePerm)
|
|
}
|