You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-weather/main.go

148 lines
3.6 KiB

package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
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() {
//set up the flags for the program to use!
var city, code string
flag.StringVar(&city, "city", "London", "Enter city e.g. London, Glasgow etc...")
flag.StringVar(&code, "code", "uk", "Enter Code e.g. uk, us etc...")
flag.Parse()
//setting up openweathermap api
api_key := "29e5139b86638988d333a28ba360bfd9"
full := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "," + code + "&units=metric" + "&appid=" + api_key + ""
fmt.Printf("\n------\nWeather url: %+s\n---------\n", full)
//read webpage
url := full
resp, err := http.Get(url)
//reads html as a slice of bytes
html, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
//print the html
fmt.Printf("%s\n", html)
fmt.Println("---------- JSON PARSED -----------\n\n")
//output the html to stirling.json
CreateFile(string(html))
data, _ := LoadConfiguration("weather.json")
fmt.Println(data)
}
func LoadConfiguration(file string) (WeatherAPI, error) {
var config WeatherAPI
configFile, err := os.Open(file)
if err != nil {
fmt.Println(err.Error())
}
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
return config, err
}
func CreateFile(fileContents string) {
// fmt package implements formatted
// I/O and has functions like Printf
// and Scanf
fmt.Printf("Writing to a file in Go lang\n")
// in case an error is thrown it is received
// by the err variable and Fatalf method of
// log prints the error message and stops
// program execution
file, err := os.Create("weather.json")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
// Defer is used for purposes of cleanup like
// closing a running file after the file has
// been written and main //function has
// completed execution
defer file.Close()
// len variable captures the length
// of the string written to the file.
len, err := file.WriteString(fileContents)
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
// Name() method returns the name of the
// file as presented to Create() method.
fmt.Printf("\nFile Name: %s", file.Name())
fmt.Printf("\nLength: %d bytes", len)
}