~kota/metweather

ref: f465ab84866d7f1c7197628097ef0514ddd3a72f metweather/cmd/forecast.go -rw-r--r-- 1.6 KiB
f465ab84Dakota Walsh add man page to gitignore 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
56
57
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: "display 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"))
}

// forecast fetches and prints a forecast based on options provided
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 using
// a provided client, context, and location
func forecastWeekly(client *metservice.Client, ctx context.Context, location string) error {
	f, _, err := client.GetForecast(ctx, location)
	if err != nil {
		return fmt.Errorf("getting forecast: %v", err)
	}
	for _, day := range f.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, "%d°C\n", *day.Max)
	}
	return nil
}