added new file go/l17.go To determine the weather using the OpenWeatherMap API
This commit is contained in:
parent
72b2086f04
commit
7928267d37
3 changed files with 48 additions and 0 deletions
47
go/l17.go
Normal file
47
go/l17.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"github.com/joho/godotenv"
|
||||
"os"
|
||||
"strings"
|
||||
"net/http"
|
||||
"time"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type OpenWeather struct{
|
||||
City string `json:"name"`
|
||||
Main struct {
|
||||
Temp float64 `json:"temp"`
|
||||
} `json:"main"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("%v\n", err)
|
||||
}
|
||||
api := os.Getenv("openweathermap")
|
||||
city := os.Getenv("city_openweather")
|
||||
client := &http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
}
|
||||
link := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
|
||||
url := strings.ReplaceAll(link, " ", "%20")
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("%v\n", err)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Fatalf("%v\n", err)
|
||||
}
|
||||
var WeatherData OpenWeather
|
||||
err = json.NewDecoder(resp.Body).Decode(&WeatherData)
|
||||
if err != nil {
|
||||
log.Fatalf("%v\n", err)
|
||||
}
|
||||
fmt.Println(WeatherData.City, WeatherData.Main.Temp)
|
||||
}
|
||||
BIN
go/output/l17
Executable file
BIN
go/output/l17
Executable file
Binary file not shown.
1
go/tempCodeRunnerFile.go
Normal file
1
go/tempCodeRunnerFile.go
Normal file
|
|
@ -0,0 +1 @@
|
|||
link := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
|
||||
Loading…
Reference in a new issue