Hello there! Today, we are going to make a Weather Tracking project in Go with the help of some important packages in Go and also you’re going to need API keys from openweathermap.org which provides historical, current, and forecasted weather data via light-speed APIs.
Prerequisites to ensure before jumping on to the project:
- Golang (latest version) installed on your computer.
- Some familiarity with Golang and its packages.
- Basic commands for using windows Powershell or command prompt.
Description of the Project:
This project will help you to know about the temperature in any city of any country in the whole world. However, by certain modifications in our Golang Program, we will be able to retrieve more information about any city but for sake of the simplicity of our program, we will one be retrieving the temperature.
Now, let’s head on to the programming part. I’ll be coding in Vs-code you can opt for any code IDE you like.
Firstly, you need to make a project root directory or a go-workspace where you can save all your go programs. You can make a file manually in an IDE or using powerShell, I prefer Windows Powershell.
So, head over to your go-workspace directory:
Now, that you’re in your root project directory make a new folder here named weather which will includes all the programming files and API keys.
Now, head over to the WEATHER directory and start writing some code:
Inside the folder make 2 files named main.go and .apiConfig file and Inside the apiConfig file add your OpenWeatherMapApiKey.
Also, do not forget to add go.mod file, a go.mod file will be created inside with the name of your project directory as the module and the version of Go you are using.
Use the command in the terminal inside your WEATHER folder:
‘go mod init’ it will add the mod file inside your project directory.
I have divided this program into a couple of functions to make it easier to understand:
- loadApiConfig: returns apiConfigData, error if any.
- hello: writes a hello greeting in http response writer.
- query: it will take input as a city name and returns weather data, error if any.
- main: it is the function where a program runs in Go.
Here is the code below:
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
)
type apiConfigData struct{
OpenWeatherMapApiKey string `json:"OpenWeatherMapApiKey"`
}
type weatherData struct{
Name string `json:"name"`
Main struct{
kelvin float64 `json:"temp"`
} `json:"main"`
}
func loadApiConfig(filename string) (apiConfigData, error){
bytes, err := ioutil.ReadFile(filename)
if err != nil{
return apiConfigData{}, err
}
var c apiConfigData
err = json.Unmarshal(bytes, &c)
if err != nil{
return apiConfigData{}, err
}
return c, nil
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello from GoLang!\n"))
}
func query(city string) (weatherData, error){
apiConfig, err := loadApiConfig(".apiConfig")
if err != nil {
return weatherData{}, err
}
resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?/APPID=" + apiConfig.OpenWeatherMapApiKey + "&q=" + city)
if err != nil {
return weatherData{}, err
}
defer resp.Body.Close()
var d weatherData
if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
return weatherData{}, err
}
return d, nil
}
func main() {
http.HandleFunc("/hello", hello)
http.HandleFunc("/weather/",
func(w http.ResponseWriter, r *http.Request) {
city := strings.SplitN(r.URL.Path, "/", 3)[2]
data, err := query(city)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(data)
})
http.ListenAndServe(":8080",nil)
}
In our code, we have used a couple of important packages let’s understand them,
- “encoding/json” will help us to encode some data for transfer.
- “io/ioutil” will help us to ReadFile (In this case .apiConfig file)
- “net/http” allows you to use an HTTP server other than the default one.
- “strings” package is used to process some string-related work in programming.
Let’s see the results via some of the screenshots:
Our hello function is working completely fine!
Let’s check our program by retrieving some of the cities temperature (in kelvin):
So, here our program runs completely fine!
Thanks for sticking out till the end.
GitHub: https://github.com/cosmic-weber/Golang/tree/main/WEATHER
Add a comment: