weather-cli/cmd/location.go

75 lines
1.5 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-08-02 23:26:28 -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-08-09 01:13:22 -04:00
log.Printf("Error reading location from server: %v\n", 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-08-09 01:13:22 -04:00
log.Printf("Error reading JSON from server: %v", 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
}
// Prompt user for coordinates
2022-08-02 23:26:28 -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
}
// Prompt user for zip code
func getZip(app *Application) {
fmt.Print("\nEnter 5-digit zip code: ")
_, err := fmt.Scanf("%s", &app.Config.Location)
if err != nil {
log.Println(err)
}
}
// Prompt user for city
func getCity(app *Application) {
fmt.Print("\nEnter city: ")
_, err := fmt.Scanf("%s", &app.Config.Location)
if err != nil {
log.Println(err)
}
}