Skip to content

Instantly share code, notes, and snippets.

@ncorreia
Created February 24, 2023 16:01
Show Gist options
  • Save ncorreia/0b6b0f4901f149d418f9c166610a837f to your computer and use it in GitHub Desktop.
Save ncorreia/0b6b0f4901f149d418f9c166610a837f to your computer and use it in GitHub Desktop.
chat gpt generated Go code to show Premier League results for a given matchday
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
)
type FullTime struct {
HomeTeamScore int `json:"home"`
AwayTeamScore int `json:"away"`
}
type FixtureResult struct {
FullTime FullTime `json:"fullTime"`
}
type Team struct {
Name string `json:"name"`
}
type Fixture struct {
Result FixtureResult `json:"score"`
Venue string `json:"venue"`
UtcDate string `json:"utcDate"`
HomeTeam Team `json:"homeTeam"`
AwayTeam Team `json:"awayTeam"`
Matchday int `json:"matchday"`
}
type FixturesResponse struct {
Fixtures []Fixture `json:"matches"`
}
func main() {
for {
fmt.Print("Enter matchday (or type 'exit' to quit): ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
input := scanner.Text()
if input == "exit" {
fmt.Println("Exiting program...")
break
}
matchday, err := strconv.Atoi(input)
if err != nil {
fmt.Println("Invalid input. Please enter a number.")
continue
}
client := &http.Client{}
req, err := http.NewRequest("GET", "https://api.football-data.org/v3/competitions/PL/matches", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("X-Auth-Token", "90400f2ccc7041dabfb49529a9d50876")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error fetching results:", err)
return
}
defer resp.Body.Close()
var fixtures FixturesResponse
err = json.NewDecoder(resp.Body).Decode(&fixtures)
if err != nil {
fmt.Println("Error decoding results:", err)
return
}
fmt.Println("Latest Premier League results (Matchday", matchday, "):")
for _, fixture := range fixtures.Fixtures {
if fixture.Result.FullTime.HomeTeamScore >= 0 && fixture.Result.FullTime.AwayTeamScore >= 0 && fixture.Matchday == matchday {
date, err := time.Parse(time.RFC3339, fixture.UtcDate)
if err != nil {
fmt.Println("Error parsing date:", err)
return
}
formattedDate := date.Format("02/01/06 3pm")
fmt.Printf("%-27s %2d - %2d %-27s %-13s [%s]\n", fixture.HomeTeam.Name, fixture.Result.FullTime.HomeTeamScore, fixture.Result.FullTime.AwayTeamScore, fixture.AwayTeam.Name, formattedDate, fixture.Venue)
}
}
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment