refactor: move function into web package

This commit is contained in:
2021-12-19 15:49:16 +01:00
parent 3b7a8e6498
commit b8e2d1de67
2 changed files with 32 additions and 29 deletions

View File

@ -3,6 +3,10 @@ package web
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
@ -20,3 +24,29 @@ func ReadJSON(url string, target interface{}) error {
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(target)
}
// GetFile downloads a file and saves it to a filepath
func GetFile(filepath string, url string) (err error) {
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}