Files
abra/pkg/web/web.go
decentral1se ff32c06676
All checks were successful
continuous-integration/drone/push Build is passing
feat: translation support
See #483
2025-08-19 16:07:24 +02:00

55 lines
1.1 KiB
Go

// Package web provides functionality for dealing with web operations.
package web
import (
"encoding/json"
"errors"
"io"
"net/http"
"os"
"time"
"github.com/leonelquinteros/gotext"
)
// Timeout is the time it takes before a web request bails out waiting for a
// request.
const Timeout = 10 * time.Second
// ReadJSON reads JSON and parses it into your chosen interface pointer
func ReadJSON(url string, target interface{}) error {
httpClient := NewHTTPRetryClient()
res, err := httpClient.Get(url)
if err != nil {
return err
}
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 errors.New(gotext.Get("bad status: %s", resp.Status))
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}