splitting into different files

master
simonkellet 2 years ago
parent 0f32422d87
commit 951a4fac6f
  1. 187
      main.go

@ -1,78 +1,11 @@
package main package main
import ( import (
"encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"log"
"net/http"
"os" "os"
"time"
"github.com/fatih/color"
) )
type WeatherAPI struct {
Coord Coord `json:"coord"`
Weather []Weather `json:"weather"`
Base string `json:"base"`
Main Main `json:"main"`
Visability int64 `json:"visibility"`
Wind Wind `json:"wind"`
Rain Rain `json:"rain"`
Clouds Cloud `json:"cloud"`
DT int64 `json:"dt"`
Sys Sys `json:"sys"`
TimeZone int `json:"timezone"`
ID int `json:"id"`
Name string `json:"name"`
COD int `json:"cod"`
}
type Coord struct {
Lon float64 `json:"lon"`
Lat float64 `json:"lat"`
}
type Weather struct {
ID int `json:"id"`
Main string `json:"main"`
Description string `json:"description"`
Icon string `json:"icon"`
}
type Main struct {
Temp float64 `json:"temp"`
Feels_like float64 `json:"feels_like"`
Temp_min float64 `json:"temp_min"`
Temp_max float64 `json:"temp_max"`
Pressure float64 `json:"pressure"`
Humidity float64 `json:"humidity"`
}
type Wind struct {
Speed float64 `json:"speed"`
Deg float64 `json:"deg"`
Gust float64 `json:"gust"`
}
type Rain struct {
T1h float64 `json:"1h"`
}
type Cloud struct {
All int `json:"all"`
}
type Sys struct {
Types int `json:"type"`
Id int64 `json:"id"`
Country string `json:"country"`
Sunrise int64 `json:"sunrise"`
Sunset int64 `json:"sunset"`
}
func main() { func main() {
//set up the flags for the program to use! //set up the flags for the program to use!
var city, code, api_key string var city, code, api_key string
@ -84,120 +17,24 @@ func main() {
full := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "," + code + "&units=metric" + "&appid=" + api_key + "" full := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "," + code + "&units=metric" + "&appid=" + api_key + ""
//read webpage //read webpage
html, _ := loadWebPage(full) html, err := loadWebPage(full)
//Create file
createFile(string(html), false)
//Load the file
data, _ := loadJson("weather.json")
//Print the weather!
printWeather(data)
removeFile("weather.json", false)
}
func loadJson(file string) (WeatherAPI, error) {
var config WeatherAPI
configFile, err := os.Open(file)
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println("4xx error, please try again!")
os.Exit(1)
} }
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
return config, err
}
func createFile(fileContents string, debugFlag bool) { //Create file
file, err := os.Create("weather.json") createFile(string(html))
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
defer file.Close()
len, err := file.WriteString(fileContents)
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
// Debug Flag
if debugFlag {
fmt.Printf("\nFile Name: %s", file.Name())
fmt.Printf("\nLength: %d bytes", len)
}
}
func removeFile(file string, debugFlag bool) {
e := os.Remove(file)
if debugFlag {
fmt.Printf("Removing file: %s", file)
}
if e != nil {
log.Fatal(e)
}
}
func loadWebPage(web_url string) ([]byte, error) { //Load the file
url := web_url data, err := loadJson("weather.json")
resp, err := http.Get(url)
//reads html as a slice of bytes
html, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
panic(err) fmt.Println("Cannot load weather.json file!")
}
return html, err
}
func iconToEmoji(icon string) {
var em string
switch icon {
case "Clouds":
em = "☁"
case "Drizzle":
em = "🌧"
case "Rain":
em = "🌧"
case "Snow":
em = "❄"
case "Clear":
em = "☀"
default:
em = "☀"
} }
fmt.Printf(em)
}
func printWeather(data WeatherAPI) {
weatherData := data
white := color.New(color.FgWhite)
boldWhite := white.Add(color.Bold)
dt := time.Now() //Print the weather!
boldWhite.Println(dt.Format("01/02/2006 15:04")) printWeather(data)
str_loc := weatherData.Name
str_code := weatherData.Sys.Country
str_weather := weatherData.Weather[0].Main
str_weather_detail := weatherData.Weather[0].Description
str_weather_icon := weatherData.Weather[0].Main
str_temp := weatherData.Main.Temp
str_temp_fl := weatherData.Main.Feels_like
str_temp_min := weatherData.Main.Temp_min
str_temp_max := weatherData.Main.Temp_max
str_sunset := time.Unix(weatherData.Sys.Sunset, 0)
str_sunrise := time.Unix(weatherData.Sys.Sunrise, 0)
boldWhite.Printf("📍Location: ") //remove the file at the end
fmt.Printf("%v, %v\n", str_loc, str_code) removeFile("weather.json")
boldWhite.Printf("Weather:")
iconToEmoji(str_weather_icon)
fmt.Printf(" %v (%v)\n", str_weather, str_weather_detail)
boldWhite.Printf("🌡 Temp: ")
fmt.Printf("%v°C (Feels like: %v°C)\n(Min: %v°C, Max: %v°C)\n", str_temp, str_temp_fl, str_temp_min, str_temp_max)
boldWhite.Printf("🌅Sunrise: ")
fmt.Printf("%v\t", str_sunrise.Format("15:04"))
boldWhite.Printf("🌇Sunset: ")
fmt.Printf("%v\n", str_sunset.Format("15:04"))
} }

Loading…
Cancel
Save