Table of Contents
Introduction
In this tutorial, we will learn how to build a weather application using Go and the OpenWeather API. By the end of this tutorial, you will have a working application that fetches the weather information for a given city and displays it to the user.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of Go programming language and familiarity with HTTP API calls. You will also need to sign up for an OpenWeather API key, which will be used to make requests and retrieve weather information.
Setup
Before we start building the application, let’s set up our project and install any necessary dependencies.
-
Create a new directory for your project:
mkdir weather-app cd weather-app
-
Initialize a new Go module:
go mod init weather-app
-
Install the required dependencies:
go get github.com/go-resty/resty/v2
We will be using the
go-resty
package for making HTTP requests.
Creating the Weather Application
Now that our project is set up, let’s start building our weather application step-by-step.
-
Create a new Go file called
main.go
:touch main.go
-
Open
main.go
in your preferred text editor. -
Import the necessary packages:
package main import ( "fmt" "log" "github.com/go-resty/resty/v2" )
-
Define the main function:
func main() { // Application logic will go here }
-
In the
main
function, create a new instance ofresty.Client
:client := resty.New()
This client will be used to make HTTP requests to the OpenWeather API.
-
Prompt the user to enter a city name:
fmt.Print("Enter a city name: ") var cityName string fmt.Scanf("%s", &cityName)
-
Make a GET request to the OpenWeather API:
response, err := client.R(). SetQueryParams(map[string]string{ "q": cityName, "appid": "YOUR_API_KEY", }). Get("https://api.openweathermap.org/data/2.5/weather")
Replace
"YOUR_API_KEY"
with your actual OpenWeather API key. -
Handle any errors that occur during the API request:
if err != nil { log.Fatalf("Failed to fetch weather data: %v", err) }
-
Parse the response body to extract the weather information:
var weatherData struct { Weather []struct { Main string `json:"main"` Description string `json:"description"` } `json:"weather"` Main struct { Temperature float64 `json:"temp"` Humidity int `json:"humidity"` } `json:"main"` } err = response.Unmarshal(&weatherData) if err != nil { log.Fatalf("Failed to parse weather data: %v", err) }
-
Display the weather information to the user:
fmt.Printf("Current weather in %s\n", cityName) fmt.Printf("Temperature: %.2f°C\n", weatherData.Main.Temperature-273.15) fmt.Printf("Humidity: %d%%\n", weatherData.Main.Humidity) fmt.Printf("Description: %s\n", weatherData.Weather[0].Description)
-
Run the application:
go run main.go
-
Test the application by entering different city names.
Congratulations! You have successfully built a weather application using Go and the OpenWeather API.
Conclusion
In this tutorial, we learned how to use Go to build a simple weather application that fetches weather information from the OpenWeather API. We covered making HTTP requests, handling API responses, and displaying the weather data to the user. You can further enhance this application by adding features such as extended forecast, user authentication, or graphical user interface. Explore the OpenWeather API documentation to discover more available endpoints and data.
Remember to handle any potential errors, such as network failures or unexpected JSON responses, to ensure a robust application. Happy coding!