ponyapi/client/go/get.go

111 lines
2.2 KiB
Go
Raw Normal View History

2015-08-13 01:07:20 +00:00
package ponyapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const (
2016-01-16 16:15:54 +00:00
endpoint = "https://ponyapi.apps.xeserv.us"
2015-08-13 01:07:20 +00:00
)
func getJson(fragment string) (data []byte, err error) {
c := &http.Client{}
2016-01-16 16:15:54 +00:00
req, err := http.NewRequest("GET", endpoint+fragment, nil)
2015-08-13 01:07:20 +00:00
if err != nil {
return nil, err
}
2016-01-16 16:15:54 +00:00
//req.Header.Add("X-API-Options", "bare")
resp, err := c.Do(req)
2015-08-13 01:07:20 +00:00
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return
}
func getEpisode(fragment string) (*Episode, error) {
data, err := getJson(fragment)
if err != nil {
return nil, err
}
ewr := &episodeWrapper{}
err = json.Unmarshal(data, ewr)
if err != nil {
return nil, err
}
return ewr.Episode, nil
}
func getEpisodes(fragment string) ([]*Episode, error) {
data, err := getJson(fragment)
if err != nil {
return nil, err
}
eswr := &episodes{}
err = json.Unmarshal(data, eswr)
if err != nil {
return nil, err
}
return eswr.Episodes, nil
}
2015-08-13 02:06:46 +00:00
// Newest returns information on the newest episode or an error.
2015-08-13 01:07:20 +00:00
func Newest() (*Episode, error) {
return getEpisode("/newest")
}
2015-08-17 21:36:24 +00:00
// LastAired returns information on the most recently aried episode
// or an error.
func LastAired() (*Episode, error) {
return getEpisode("/last_aired")
}
2015-08-13 02:06:46 +00:00
// Random returns information on a random episode.
2015-08-13 01:07:20 +00:00
func Random() (*Episode, error) {
return getEpisode("/random")
}
2015-08-13 02:06:46 +00:00
// GetEpisode gets information about season x episode y or an error.
2015-08-13 01:07:20 +00:00
func GetEpisode(season, episode int) (*Episode, error) {
return getEpisode(fmt.Sprintf("/season/%d/episode/%d", season, episode))
}
2015-08-13 02:06:46 +00:00
// AllEpisodes gets all information on all episodes or returns an error.
2015-08-13 01:07:20 +00:00
func AllEpisodes() ([]*Episode, error) {
return getEpisodes("/all")
}
2015-08-13 02:06:46 +00:00
// GetSeason returns all information on season x or returns an error.
2015-08-13 01:07:20 +00:00
func GetSeason(season int) ([]*Episode, error) {
return getEpisodes(fmt.Sprintf("/season/%d", season))
}
2015-08-13 02:06:46 +00:00
// Search takes the give search terms and uses that to search the
// list of episodes.
2015-08-13 01:07:20 +00:00
func Search(query string) ([]*Episode, error) {
path, err := url.Parse("/search")
if err != nil {
panic(err)
}
q := path.Query()
q.Set("q", query)
path.RawQuery = q.Encode()
return getEpisodes(path.String())
}