Introduction
Accessing weather information programmatically is a common use case in modern applications. This program demonstrates how to fetch and display weather information using a public weather API in the Go programming language. The program utilizes HTTP requests to interact with the API and processes the JSON response to display weather details in a readable format.
Objective
The goal of this program is to make an HTTP request to a weather API, parse the JSON response, and display the weather information for a given city. This tutorial is aimed at developers looking to integrate API consumption into their Go applications.
Code
package main import ( "encoding/json" "fmt" "net/http" "os" ) // WeatherResponse represents the structure of the API response type WeatherResponse struct { Name string `json:"name"` Main struct { Temp float64 `json:"temp"` Humidity int `json:"humidity"` } `json:"main"` Weather []struct { Description string `json:"description"` } `json:"weather"` } func main() { // Replace with your API key and city apiKey := "your_api_key_here" city := "London" // Build the API URL apiURL := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, apiKey) // Make the HTTP request response, err := http.Get(apiURL) if err != nil { fmt.Fprintf(os.Stderr, "Error fetching weather data: %v\n", err) os.Exit(1) } defer response.Body.Close() // Decode the JSON response var weather WeatherResponse if err := json.NewDecoder(response.Body).Decode(&weather); err != nil { fmt.Fprintf(os.Stderr, "Error decoding weather data: %v\n", err) os.Exit(1) } // Display the weather information fmt.Printf("Weather in %s:\n", weather.Name) fmt.Printf("Temperature: %.2f°C\n", weather.Main.Temp) fmt.Printf("Humidity: %d%%\n", weather.Main.Humidity) if len(weather.Weather) > 0 { fmt.Printf("Description: %s\n", weather.Weather[0].Description) } }
Explanation
This program performs the following steps:
- Import necessary packages: The program uses
net/http
for making HTTP requests,encoding/json
for parsing JSON responses, andos
for error handling. - Define a structure: The
WeatherResponse
struct maps to the JSON structure returned by the weather API. - Construct the API request: The API URL is built dynamically using the city name and API key.
- Make the API call: The program sends an HTTP GET request to the weather API and handles errors.
- Parse the JSON response: The response is decoded into the
WeatherResponse
struct for easy access to data. - Display the weather: Weather details such as temperature, humidity, and description are printed in a user-friendly format.
How to Run
- Sign up for an API key at OpenWeather.
- Replace
your_api_key_here
in the code with your API key. - Install Go from the official Go website.
- Copy the code into a file named
fetch_weather.go
. - Run the program using the command:
go run fetch_weather.go
- Observe the weather information for the specified city in the terminal.
Dear CEO,
We are an investment and funding firm, working in alliance with a high-net-worth group to provide financing at minimal interest rates. We believe that a strategic partnership between our organizations could create substantial value for both parties.
We would be delighted to share more details about this opportunity upon your response. Please feel free to reach out if you require any additional information or would like to discuss this further.
Looking forward to your thoughts.
Best regards,
Art Allen