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" ) // GetFavorites retrieves a user's favorite posts from the e621 API. // // The user_id parameter is required to get the favorites of a user. // // Parameters: // - requestContext: The context for the API request, including the host, user agent, username, and API key. // - query: A map containing additional query parameters for the API request. // // Returns: // - []model.Post: A slice of favorite posts. // - error: An error, if any, encountered during the API request or response handling. func GetFavorites(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) { // Create a new HTTP GET request. r, err := http.NewRequest("GET", fmt.Sprintf("%s/favorites.json", requestContext.Host), nil) if err != nil { return nil, err } // Append query parameters to the request URL. 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 { return nil, 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 nil, utils.StatusCodesToError(resp.StatusCode) } // Initialize a User struct to store the response data. var favoriteResponse model.PostResponse // Decode the JSON response into the user struct. err = json.NewDecoder(resp.Body).Decode(&favoriteResponse) if err != nil { // Log the error and return an empty User struct and the error. return nil, err } return favoriteResponse.Posts, nil }