~kota/metweather

ref: de059fd94b3c0a35c77b9e89f941506fcf7fb9bd metweather/cmd/forecast.go -rw-r--r-- 1.4 KiB
de059fd9Dakota Walsh update test with location 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package cmd

import (
	"context"
	"fmt"
	"log"

	"git.sr.ht/~kota/metservice-go"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// forecastCmd represents the forecast command
var forecastCmd = &cobra.Command{
	Use:   "forecast",
	Short: "displays weather predictions for the current day or next serveral days",
	Run:   forecast,
}

func init() {
	rootCmd.AddCommand(forecastCmd)
	forecastCmd.PersistentFlags().StringP("location", "l", "", "Location used for the weather forecast")
	viper.BindPFlag("location", forecastCmd.PersistentFlags().Lookup("location"))
}

func forecast(cmd *cobra.Command, args []string) {
	client := metservice.NewClient()
	ctx := context.Background()
	location := viper.GetString("location")
	if location == "" {
		log.Fatal("location is required either using the flag or config")
	}
	err := forecastWeekly(client, ctx, location)
	if err != nil {
		log.Fatal(err)
	}
}

// forecastWeekly fetches and prints a forecast on one line for each day
func forecastWeekly(client *metservice.Client, ctx context.Context, location string) error {
	forecast, _, err := client.GetForecast(ctx, location)
	if err != nil {
		return fmt.Errorf("getting forecast: %v", err)
	}
	for _, day := range forecast.Days {
		fmt.Fprintf(out, "%d-%d-%d ",
			day.Date.Local().Year(),
			day.Date.Local().Month(),
			day.Date.Local().Day())
		fmt.Fprintf(out, "%s ", *day.ForecastWord)
		fmt.Fprintf(out, "%d-", *day.Min)
		fmt.Fprintf(out, "%dc\n", *day.Max)
	}
	return nil
}