Golang
Golang

 

 

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:

  1. Import necessary packages: The program uses net/http for making HTTP requests, encoding/json for parsing JSON responses, and os for error handling.
  2. Define a structure: The WeatherResponse struct maps to the JSON structure returned by the weather API.
  3. Construct the API request: The API URL is built dynamically using the city name and API key.
  4. Make the API call: The program sends an HTTP GET request to the weather API and handles errors.
  5. Parse the JSON response: The response is decoded into the WeatherResponse struct for easy access to data.
  6. Display the weather: Weather details such as temperature, humidity, and description are printed in a user-friendly format.

How to Run

  1. Sign up for an API key at OpenWeather.
  2. Replace your_api_key_here in the code with your API key.
  3. Install Go from the official Go website.
  4. Copy the code into a file named fetch_weather.go.
  5. Run the program using the command:
                    go run fetch_weather.go
    
  6. Observe the weather information for the specified city in the terminal.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

One thought on “Go Program to Fetch Weather Information Using an API”
  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)