package callapiutils import ( "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" ) func AddQueryParamInt(u *url.URL, paramName string, paramValue int) { AddQueryParam(u, paramName, strconv.Itoa(paramValue)) } func AddQueryParam(u *url.URL, paramName string, paramValue string) { q := u.Query() q.Set(paramName, paramValue) u.RawQuery = q.Encode() } func FetchAndParseResult[T any](u *url.URL, queryResult *T) error { resp, err := DoApiQuery(u) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { bodyError, err := io.ReadAll(resp.Body) if err != nil { return err } return fmt.Errorf("Call to %s returned code %d:\n%s", u.String(), resp.StatusCode, string(bodyError)) } decoder := json.NewDecoder(resp.Body) err = decoder.Decode(queryResult) if err != nil { return err } return err } func DoApiQuery(u *url.URL) (*http.Response, error) { client := &http.Client{} req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } req.Header.Add("Accept", "application/json") req.Header.Add("User-Agent", "PersonalLibraryManager/0.1 (artlef@protonmail.com)") return client.Do(req) } func ComputeUrl(baseUrl string, paths ...string) (*url.URL, error) { u, err := url.Parse(baseUrl) if err != nil { return nil, err } for _, p := range paths { u = u.JoinPath(p) } return u, nil }