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
Dear In,
I recently lost my daughter to leukemia. She was passionate about music and dreamt of becoming a professional pianist. Her Yamaha piano meant the world to her, and I would love for it to find a new home with someone who shares her passion.
If you or anyone you know would be interested in continuing her legacy through music, please let me know.
Warm regards,
Irene
Hi,
Your website (in.net) is so good, can you just review our website for link sharing, please give us feedback,
https://afshinkalhori.ir/best-season-to-explore-the-world
our e-mail address is: afsoriproject@gmail.com
Its great honor for our team to work with such admin like you.
Thank you my friend,
————————————-
Also there is helpful link for making money easily with only share your internet:
https://afshinkalhori.ir/pawns.app
DearIn,
I hope this message finds you well. I have a compelling business proposal that offers significant benefits for both parties, creating a win-win opportunity for collaboration.
I’d love to share more details and explore how we can work together to achieve mutual success. Please feel free to reach out at your earliest convenience.
Looking forward to your response.
Best regards,
Steven Pember
Hello
I wanted to see if you would be open to rejuvenating your website with our complete website package.
We are giving away free websites right now, you only pay for maintenance.
Here is what you get
1. We rejuvenate your business website
2. We service your business website monthly with maintenance and provide you 60 minutes every month of page updates to keep your website up to date for your business, all included.
And You Get a one-time completely free on-site SEO. Yes, no SEO subscriptions with us!
All of this for only $97 a month! For real..
And the best part is there is no setup fee!
We are doing this because we do not believe its fair for businesses to pay so much for a great website.
Click Here to Get Started
http://www.websolutionsgenius.com/topflightwebsites/
Sending You Success
Subject: Fix in.net’s GDPR gap in 5 min
Hi there,
⚠️ Your site is missing a cookie banner, has no working privacy-policy link, and scores 58/100 on accessibility—putting you in the $2-7k GDPR/CPRA fine zone.
Our one-time Compliance Kit patches all three in under 5 minutes (privacy page, 2 kB cookie banner, a11y toggle).
Get compliant now → https://complianceservice.solutions/
— Adam, Compliance Service
support@complianceservice.solutions
Reply STOP to opt out