From 0dd65dd062362f913b3028e07e2f0c3afaec8894 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Mon, 31 Jan 2022 11:25:04 +0530 Subject: Added a URL Generator --- anime/anime.go | 12 +++++++++--- anime/util.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) (limited to 'anime') diff --git a/anime/anime.go b/anime/anime.go index 7e5cf70..2c23209 100644 --- a/anime/anime.go +++ b/anime/anime.go @@ -2,8 +2,9 @@ package anime import ( "encoding/json" + "errors" "fmt" - "errors" + "strconv" ) // Each anime has its own ID on MAL @@ -18,13 +19,18 @@ func GetAnimeById(token string, animeId int) Anime { } // Ranking is a list of anime sorted by their rank -func GetAnimeRanking(token string, rankingType string) (AnimeRanking, error) { +func GetAnimeRanking(token string, rankingType string, limit int) (AnimeRanking, error) { var animeRanking AnimeRanking if !isValidRankingType(rankingType) { return animeRanking, errors.New(fmt.Sprintf("GetAnimeRanking: Invalid Ranking Type Given (\"%s\")", rankingType)) } - endpoint := "https://api.myanimelist.net/v2/anime/ranking?ranking_type=all&limit=4" + endpoint, _ := urlGenerator( + "https://api.myanimelist.net/v2/anime/ranking", + []string{"ranking_type", "limit"}, + [][]string{{rankingType}, {strconv.Itoa(limit)}}, + true, + ) // gets data from API and stores it in a struct var rankingData RawRanking diff --git a/anime/util.go b/anime/util.go index 319bbc9..f09f189 100644 --- a/anime/util.go +++ b/anime/util.go @@ -4,8 +4,11 @@ import ( "io/ioutil" "log" "net/http" + "errors" ) +// Handles HTTP request with your OAuth token as a Header +// TODO: Verify that this function is safe to use func requestHandler(token string, endpoint string) string { client := &http.Client{} @@ -31,3 +34,40 @@ func requestHandler(token string, endpoint string) string { return string(body) } + +func urlGenerator(baseUrl string, names []string, values [][]string, isPrimary bool) (string, error) { + // TODO: error if cap(names) != cap(values) + if cap(names) != cap(values) { + return "", errors.New("urlGenerator: Error: Length of names and values don't match.") + } + + var fields string + + for index, name := range(names) { + var data string + /* if the data is the first field in URL, + * it goes like ?key=value + * else it is &nextkey=value */ + if isPrimary { + data = "?" + name + "=" + } else { + data = "&" + name + "=" + } + + // add values to data variable + for i, j := range values[index] { + if i > 0 { + data = data + "," + j + } else { + data = data + j + } + } + + fields = fields + data + + // from now on all other fields will be secondary + isPrimary = false + } + + return baseUrl + fields, nil +} -- cgit v1.2.3