82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
package espn
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"git.chandlerswift.com/chandlerswift/bannergen/internal/types"
|
|
)
|
|
|
|
type ESPNDataFetcher struct{}
|
|
|
|
func (ESPNDataFetcher) Fetch() (sports []types.Sport) {
|
|
sportNames := []string{"hockey/nhl"}
|
|
|
|
type ApiResponse struct {
|
|
Sports []struct {
|
|
Name string `json:"name"`
|
|
Leagues []struct {
|
|
Teams []struct {
|
|
Team struct {
|
|
Slug string `json:"slug"`
|
|
Abbreviation string `json:"abbreviation"`
|
|
DisplayName string `json:"displayName"`
|
|
Color string `json:"color"`
|
|
AlternateColor string `json:"alternateColor"`
|
|
Logos []struct {
|
|
Href string `json:"href"`
|
|
} `json:"logos"`
|
|
} `json:"team"`
|
|
} `json:"teams"`
|
|
} `json:"leagues"`
|
|
} `json:"sports"`
|
|
}
|
|
|
|
for _, sportName := range sportNames {
|
|
res, err := http.Get(fmt.Sprintf("https://site.api.espn.com/apis/site/v2/sports/%v/teams", sportName))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if res.StatusCode != 200 {
|
|
panic(res.StatusCode)
|
|
}
|
|
data, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var apiResponse ApiResponse
|
|
if err := json.Unmarshal([]byte(data), &apiResponse); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
if len(apiResponse.Sports) == 0 {
|
|
panic("empty apiResponse.Sports")
|
|
}
|
|
// Use the first sport
|
|
sport := types.Sport{
|
|
Name: apiResponse.Sports[0].Name,
|
|
}
|
|
|
|
// Iterate through leagues and teams
|
|
for _, league := range apiResponse.Sports[0].Leagues {
|
|
for _, t := range league.Teams {
|
|
team := types.Team{
|
|
Slug: t.Team.Slug,
|
|
Abbreviation: t.Team.Abbreviation,
|
|
DisplayName: t.Team.DisplayName,
|
|
Logo: t.Team.Logos[0].Href, // Use the first logo
|
|
Color: t.Team.Color,
|
|
AlternateColor: t.Team.AlternateColor,
|
|
}
|
|
sport.Teams = append(sport.Teams, team)
|
|
}
|
|
}
|
|
|
|
sports = append(sports, sport)
|
|
}
|
|
return
|
|
}
|