weather-cli/cmd/location.go

59 lines
1.1 KiB
Go
Raw Normal View History

2022-07-07 23:43:16 -04:00
package main
import (
2022-07-08 22:13:16 -04:00
"bufio"
2022-07-07 23:43:16 -04:00
"encoding/json"
2022-07-08 22:13:16 -04:00
"fmt"
2022-07-07 23:43:16 -04:00
"io/ioutil"
"log"
"net/http"
2022-07-08 22:13:16 -04:00
"os"
2022-07-07 23:43:16 -04:00
"strings"
)
2022-07-26 22:22:05 -04:00
// Use WAN address to obtain location data
2022-07-08 22:13:16 -04:00
func getLocation(app *application) {
2022-07-07 23:43:16 -04:00
res, err := http.Get("https://ipinfo.io/json")
if err != nil {
2022-07-08 22:13:16 -04:00
fmt.Println("Unable to automatically obtain location, please try again.")
2022-07-07 23:43:16 -04:00
log.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
2022-07-08 04:01:38 -04:00
log.Println(err)
2022-07-07 23:43:16 -04:00
}
2022-07-08 22:13:16 -04:00
err = json.Unmarshal(body, &app.Config)
2022-07-07 23:43:16 -04:00
if err != nil {
2022-07-08 04:01:38 -04:00
log.Println(err)
2022-07-07 23:43:16 -04:00
}
2022-07-08 22:13:16 -04:00
loc := strings.Split(app.Config.Location, ",")
app.Config.Latitude, app.Config.Longitude = loc[0], loc[1]
2022-07-07 23:43:16 -04:00
}
2022-07-26 22:22:05 -04:00
// Prompt user for location
2022-07-08 22:13:16 -04:00
func getPreciseLocation(app *application) {
2022-07-07 23:43:16 -04:00
2022-07-11 19:07:24 -04:00
fmt.Print("\nEnter latitude: ")
2022-07-08 22:13:16 -04:00
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
log.Println(err)
}
2022-07-11 19:07:24 -04:00
app.Config.Latitude = strings.TrimSuffix(input, "\n")
2022-07-08 22:13:16 -04:00
2022-07-11 19:07:24 -04:00
fmt.Print("\nEnter longitude: ")
2022-07-08 22:13:16 -04:00
input, err = reader.ReadString('\n')
if err != nil {
log.Println(err)
}
2022-07-11 19:07:24 -04:00
app.Config.Longitude = strings.TrimSuffix(input, "\n")
2022-07-07 23:43:16 -04:00
}