This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
e621-sdk-go/pkg/e621/endpoints/executer.go
SoXX 9669eb8ddf refactor: removed code duplication
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:02:15 +01:00

59 lines
1.7 KiB
Go

package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
func getRequest[T any](requestContext model.RequestContext, e621Endpoint string, query map[string]string) (T, error) {
var base T
// Create a new HTTP GET request to fetch user information from the specified 'host' and 'username'.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", requestContext.Host, e621Endpoint), nil)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Append query parameters to the request URL.
if query != nil {
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return base, utils.StatusCodesToError(resp.StatusCode)
}
// Decode the JSON response into the User struct.
err = json.NewDecoder(resp.Body).Decode(&base)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Return the user information and no error (nil).
return base, nil
}