|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + |
| 11 | + "github.com/lensesio/tableprinter" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + scoresEndpoint = "/ticker/live-or-past/wm2022" |
| 17 | +) |
| 18 | + |
| 19 | +type Score struct { |
| 20 | + Competition string `header:"Competition" json:"competition"` |
| 21 | + Venue string `header:"Venue" json:"venue"` |
| 22 | + Team1 Team `json:"team1"` |
| 23 | + Goals1 int `json:"goals1"` |
| 24 | + Team2 Team `json:"team2"` |
| 25 | + Goals2 int `json:"goals2"` |
| 26 | + Match string `header:"Match"` |
| 27 | + Goals string `header:"Goals"` |
| 28 | + Events []Event `json:"events"` |
| 29 | + MostRecentEventText string `header:"Last Event"` |
| 30 | +} |
| 31 | + |
| 32 | +type Team struct { |
| 33 | + Name string `header:"Name" json:"name"` |
| 34 | +} |
| 35 | + |
| 36 | +type Event struct { |
| 37 | + Text string `header:"Event" json:"eventText"` |
| 38 | +} |
| 39 | + |
| 40 | +var scoresCmd = &cobra.Command{ |
| 41 | + Use: "scores", |
| 42 | + Short: "Print sports tournament scores info", |
| 43 | + Long: `Print sports tournament scores info`, |
| 44 | + Run: func(cmd *cobra.Command, args []string) { |
| 45 | + s, err := refreshScores() |
| 46 | + if err != nil { |
| 47 | + fail(err) |
| 48 | + } |
| 49 | + |
| 50 | + if Output == "table" { |
| 51 | + printer := tableprinter.New(os.Stdout) |
| 52 | + items := s |
| 53 | + printer.Print(items) |
| 54 | + return |
| 55 | + } |
| 56 | + if Output == "csv" { |
| 57 | + for _, score := range s { |
| 58 | + fmt.Printf("%s %s %s %s %s\n", score.Competition, score.Venue, score.Match, score.Goals, score.Events[0].Text) |
| 59 | + } |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + fail(errors.New("unrecognized output format")) |
| 64 | + }, |
| 65 | +} |
| 66 | + |
| 67 | +func refreshScores() ([]*Score, error) { |
| 68 | + resp, err := http.Get(fmt.Sprintf("%s%s", baseURL, scoresEndpoint)) |
| 69 | + if err != nil { |
| 70 | + return []*Score{}, nil |
| 71 | + } |
| 72 | + |
| 73 | + defer resp.Body.Close() |
| 74 | + data, err := io.ReadAll(resp.Body) |
| 75 | + if err != nil { |
| 76 | + return []*Score{}, err |
| 77 | + } |
| 78 | + |
| 79 | + var scores []*Score |
| 80 | + err = json.Unmarshal(data, &scores) |
| 81 | + if err != nil { |
| 82 | + return []*Score{}, err |
| 83 | + } |
| 84 | + |
| 85 | + for _, score := range scores { |
| 86 | + score.Match = fmt.Sprintf("%s vs. %s", score.Team1.Name, score.Team2.Name) |
| 87 | + score.Goals = fmt.Sprintf("%d:%d", score.Goals1, score.Goals2) |
| 88 | + score.MostRecentEventText = score.Events[0].Text |
| 89 | + } |
| 90 | + |
| 91 | + return scores, nil |
| 92 | +} |
| 93 | + |
| 94 | +func init() { |
| 95 | + rootCmd.AddCommand(scoresCmd) |
| 96 | +} |
0 commit comments