Building a Weather App in Go using OpenWeather API (original) (raw)
Description :
In this tutorial, we will build a simple weather application using the Go programming language and the OpenWeather API. This project will help you understand how to :
- 1- Fetch data from an external API using Go.
- 2- Parse JSON responses in Go.
- 3- Handle user input and API errors gracefully.
- 4- Store API keys securely using an environment file.
Prerequisites :
Before we begin, make sure you have the following installed :
- 1- Go (version 1.18 or later)
- 2- A text editor (e.g., VS Code, GoLand, or Vim)
- 3- A terminal(Command Prompt, PowerShell, or Terminal on macOS/Linux)
Getting an OpenWeather API Key :
Before we start coding we need OpenWeather API first.
To fetch weather data, we will use the OpenWeather API . OpenWeather provides free and paid access to weather data worldwide, including current weather, forecasts, and historical data. It is widely used by developers and businesses to integrate weather information into their applications.
Your API key is very important! Without it, you won't be able to access weather data from OpenWeather. This key is used to authenticate your requests and retrieve real-time weather information.
Follow these steps to get your API key :
- 1- Go to the official OpenWeather website.
- 2- Create a free account by entering your email, username, and password.
- 3- After confirming your email and logging in, navigate to the API Keys section in your dashboard.
- 4- Copy the default API key provided (it may take a few minutes to become active).
We will use this API key in our Go application to authenticate requests to the OpenWeather API. Make sure to keep your API key private and never share it publicly to prevent unauthorized access.
Setting Up the Project
After getting an OpenWeather API Key and before writing any code, we need to set up our Go project properly :
1. Create a New Project Folder
navigate to the location where you want to store your project. Then, create a new folder for the project and navigate into it : in my case i choosed this name : weather-app
2. Initialize a Go Module
A Go module is required to manage dependencies. Run the following command to initialize your Go module :
go mod init weather-appThis will create a go.mod file that keeps track of dependencies and module information.
3. Create the Main Go File
Inside the weather-app folder, create a new file named main.go. This will be the entry point of our application.
4. Create a .env File
Since our API key should be kept private, we will store it in a .env file instead of hardcoding it in the code.
Create a new file named .env in the project folder .
Open the .env file and add your OpenWeather API key :
API_KEY=your_api_key_hereOf course, you should replace your_api_key_here by your true OpenWeather API key
Example :
API_KEY=83hjc5c4d483sd357491ffhkju70Do not share this (.env) file or push it to version control (e.g., GitHub). You can add a .gitignore file to exclude it.
Now,in the step 5, let’s see how to use godotenv in a Go program to load and print our API key.
5. Install Dependencies(godotenv)
We will use an external package to help us load environment variables securely.
Install it using this command in your terminal :
go get github.com/joho/godotenvWhy Use "godotenv"?
When working on projects that require sensitive information like API keys, it's a bad practice to hardcode them directly into your code. Instead, it's best to store them in a .env file, which keeps them separate from the main codebase and prevents accidental exposure, especially when using version control like Git. However, Go does not have built-in support for.envfiles, which is why we use thegodotenvpackage. This package reads the.envfile and loads its variables into Go’s environment, making them accessible through os.Getenv("VARIABLE_NAME").
What Does godotenv Do?
- 1- Reads a
.envfile from your project directory. - 2- Parses key-value pairs from the file.
- 3- Loads them into the environment variables of your Go application.
- 4- Prevents accidental exposure of sensitive data.
Now, let's test it
Now, let’s see how to use godotenv in a Go program to load and print our API key.
Open you main.go file and write this code.
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
// Load the .env file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Retrieve the API key
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
log.Fatal("API_KEY is not set in .env file")
}
fmt.Println("Your API Key is:", apiKey)
}
In the terminal Execute your program :
go run main.goIf everything works fine, you should see something like this :
Your API Key is: 07bd45gg4sfd56gjghjnx145How This Works :
- 1-
godotenv.Load()reads the .env file and loads its variables into the environment. - 2-
os.Getenv("API_KEY")retrieves the stored API key. - 3- If the key is missing, an error message is displayed.
With this setup, our API key is securely stored and loaded dynamically at runtime. Now we are ready to write the code for fetching weather data!
Before continuing, you can support me to keep creating great content!
💻 I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! 🙌