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.

35 thoughts 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. Hi,

    I’m Joumana, a Canadian artist behind JoumanaArt. My work celebrates vibrant colors and detailed compositions, aiming to connect and inspire.
    I’m reaching out to explore custom art opportunities with you.

    For a taste of my style, please visit my website https://www.joumanaart.com/
    Instagram @thejoumanaart (https://www.instagram.com/thejoumanaart/)
    Artsy: https://www.artsy.net/artist/joumana-yaghi

    If you’re interested in discussing possible projects, I’d be happy to connect.

    Best,
    Joumana

  8. Hi there,

    We took a look at in.net and noticed it’s showing up after some of your competitors when customers search for your services. That means people looking for what you offer might be finding them first.

    Think of SEO like setting up shop on the busiest street in town—when people search online, they’re far more likely to walk into your “store” if it’s front and center.

    We believe in making SEO simple, transparent, and results-driven. No contracts, no gimmicks—just steady work that helps your business move forward.

    For $499/month, you’ll get access to consistent SEO support, plus a detailed breakdown each month showing exactly what we’ve done and the progress being made.

    Why businesses choose us:

    No long-term contracts: Stay only if you see value.

    Clear reporting: Crystal-clear updates on every step we take.

    Flat $499 fee: No hidden extras, ever.

    Based in the USA: Licensed, insured, and easy to reach.

    Interested in learning more?

    https://simplybuiltdigital.com/seoservices/

  9. Hello

    Is managing social media holding you back?

    Having a Social Media Manager keeps your business present on every platform: all popular social media channels.

    Increases visibility, and frees up your schedule. More engagement, more growth without the daily hassle.

    Want to try this for your business? Test it today and feel the impact.

    Just reply to this email for more information.

    Best regards,
    Roseanna

    Germany, BY, Obernburg, 63777, Rudolstaedter Strasse 75
    To stop any further communication through your website form, Please reply with subject: Unsubscribe !in.net

  10. Hello,

    We ran a 30-second scan of In Net and found:
    – No cookie-consent banner detected
    – Privacy-policy link missing/404
    – Accessibility score 68/100 (Lighthouse)

    These gaps put the site inside the €2–7k GDPR/CPRA fine bracket.
    Fixing it is painless: our 5-minute kit adds a compliant privacy page, a 2 kB cookie banner, and an a11y toggle.

    See for more details → complianceservice.solutions

    — Adam @ Compliance Service
    support@complianceservice.solutions

    Reply STOP to unsubscribe

  11. Hello

    Use your phone as a $hundred-dollar-a-day money maker

    I make $more than $100 whenever I email my list with *Email Cash Machine* — ready-to-use email swipes, no-cost autoresponder, secret affiliate offers included. No need to create products, run ads, or have experience. Get paid anywhere from your phone or laptop.

    Claim your lifetime access now for just $seventeen dollars — 180-day money-back guarantee ==> https://rb.gy/uxe0l2

    Best regards
    Jacki

    If you wish to unsubscribe, please reply to this email.

  12. Hi in.net team,

    I just wanted to reach out personally and say hello.

    Lately, I’ve been noticing how many businesses are cutting down on repetitive tasks by using AI agents instead of adding extra staff.
    It’s been interesting to see how much time and cost this can save, while also freeing people up to focus on the parts of the business that really need a human touch.

    If you’re curious, I’d be happy to share my screen and walk you through how it could look in your own setup.

    no pressure, just a quick conversation to see if it’s useful.

    Would you have a little time this week for a chat?

    Best,
    Jay
    Satori Online
    https://satori-online.com/satori-online

  13. Hello

    This message is intended for the administrator of in.net. If you are not the person responsible for running the site, please kindly pass this email to the right contact.

    We are a company that provides professional SEO services. We can help your website gain more visibility online and increase your leads. Here are some of the services we offer:

    – Google Ranking Optimization
    – Google Maps Ranking
    – YouTube SEO
    – SEO Backlinks & Link Diversity
    – Website Traffic Campaigns
    – High-Quality Content Creation
    – Engaging Video Content
    – Full Social Media Management
    – Targeted Lead Acquisition
    – White-Label SEO for Agencies

    If you are the site owner, we would be glad to provide more details and discuss how we can assist your business in achieving better rankings and customer growth.

    Reply today and we’ll suggest the ideal SEO plan for your needs.

    Best regards,
    Your SEO & Digital Marketing Expert

    United Kingdom, NA, Deopham, Nr18 9st, 55 Whitby Road
    To stop any further communication from us, please reply to this email with subject: Unsubscribe !in.net

  14. Hi,

    We make sublimated sports bags, backpacks, and sportswear. To get delivery prices, please:

    1. Visit hillapex.com and pick an item.
    2. Let us know your order quantity.
    3. Provide your country name.

    Best regards
    Saad Afzal
    Founder | Hill Apex
    Email: saad@hillapex.com
    Website: hillapex.com
    Phone/WhatsApp: +92 300 7101027
    Address: Chenab Ranger’s Road, 51310 Sialkot, Pakistan

  15. I made $100/day with this simple system

    Done-for-you system, instant commissions, no tech skills needed.

    Start today before the price rises: https://rb.gy/uxe0l2

    If you wish to unsubscribe, please reply to this email.

  16. Calling all punters, tipsters & football lovers!
    Whether you’re in London, Lagos, Lima or Laos, here’s your risk-free ticket to steady weekly profit.
    How it works – in 3 simple steps
    1. Subscribe once → send any message to subscription@toxylact.com
    2. Receive this week’s picks FREE – no credit card, no up-front fee.
    3. Pay only if we deliver – at the end of the week simply wire £13 if our ROI was ≥ 8 %.
    • If ROI is below 8 % → you keep getting the next week(s) absolutely free until we bounce back.
    ________________________________________
    ✅ Proof, not promises
    Below is a snapshot of last month’s public demo sheet (all leagues, all markets).
    Note: public tips include picks below the 64 % threshold, so overall ROI looks modest – our private subscriber list sees only the ≥ 64 % batch.
    Table
    Copy
    Month Picks Wins Net Units ROI
    07/2025 90 59.57 +4.57 5.1 %
    06/2025 55 50.89 +25.89 47.1 %
    Total 145 110.46 +30.46 21.0 %
    Average odds we target: 3.2 – 8.5 → every winning ticket multiplies your stake fast.
    ________________________________________
    Want even more magic?
    Unlock Merlin – the Magical Football Predictor and watch your ROI explode into double digits every week.
    Discover Merlin here: https://merlin.toxylact.com
    ________________________________________
    Ready to join?
    Just drop a blank email or your name + country to subscription@toxylact.com and the first profitable week is on us.
    No risk. No hype. Many green numbers.
    To your next winning ticket,

  17. Hi Mom’s & Dedy,
    As a new mom, you want every drop of your breast milk to nourish—not harm—your baby.
    Toxylact.com is the only free, evidence-based tool that tells you in seconds how toxic your milk may become after you take any prescription, OTC drug, or herbal supplement.
    Why thousands of mothers trust Toxylact:
    • Instant, research-backed safety ratings for 1,500+ medications
    • Clear “safe / caution / avoid” traffic-light labels
    • Dose-adjusted calculations for premature or low-birth-weight infants
    • Mobile-friendly—check safety while you’re still at the pharmacy counter
    • Anonymous, no sign-up required, always free
    One click now can save weeks of worry later.
    Check your medication → http://www.toxylact.com
    To a healthy start for you and your baby,
    Dimitar Kehayov MD, PhD
    Manager, Toxylact.com

  18. Hi,

    I noticed a few issues on your website in.net

    Would you like me to show you what they are?

    Regards,
    Kevin

    France, LANGUEDOC-ROUSSILLON, Perpignan, 66000, 13 Rue Clement Marot, 471718372

    Don’t want to receive messages like this in the future? Just reply to this email.

  19. Hello,

    Want more visitors and clients for your in.net?

    As a bonus, we can offer you a free SEO Audit and a free SEO Backlinks service.

    We help websites get real visitors and real clients through proven online marketing methods.

    Would you like a quick free analysis of your site’s potential?

    Best regards,
    Marquis from Digital Marketing Team

    Switzerland, NA, Les Rasses, 1452, Studhaldenstrasse 123

    To stop any further communication through your website form, Please reply with subject: Unsubscribe !in.net

  20. Hi, I’m Hapei, we have a few potential clients that are interested in your services, thought you might be a good fit. I’d love to talk about the details, when do you have time to talk?

    Best,
    Hapei
    Founder | CEO

  21. Hello,

    Your website has some issues, take a look: https://www.seoptimer.com/in.net

    We can help fix these issues and improve your backlink profile.

    Claim your first SEO Backlink service for free, so you can see results before committing.

    Are you interested?

    Best regards,
    Charolette from Digital Marketing Team

    United States, MT, Polson, 59860, 3971 Coolidge Street
    To stop any further communication through your website form, Please reply with subject: Unsubscribe !in.net

  22. Hi there,

    If in.net needs help getting up to $500K in funding, I’d love to help. This is exactly what we do.

    Every week we help businesses like In Net get approved for $25K–$500K in funding – even if they’ve been denied before or are unsure if they’ll qualify.

    The best part? We make the process simple and quick.

    If you’re:
    Looking to grow your business,
    Consolidate or reconcile debt,
    Invest in research and development,
    Upgrade equipment or buy new assets…

    Then let’s talk.

    We’ve helped thousands of clients and have a 4.8-star rating on TrustPilot with hundreds of verified reviews.

    Just hit reply to this email and tell me:

    That you’re interested, or
    A time next week that works for a quick call.

    No pressure – just helpful advice and expert guidance to see what’s possible for your situation.

    Looking forward to hearing from you,
    Mable

  23. Nigeria Christins are bleeding!!!.

    We implore your support to rescue the victimised Christians in Nigeria.

    Our foundation is working with the locals to sake financial and resources support from the general public from across the world. Our team that provides holistic care, focusing on physical, psychological, social, and spiritual need.

    We need

    1. Food to feed the over one million internally displaced people (IDP) in the various camps. As of November 2024, DTM statistics identified a total of 1,322,766 IDPs in 225,458 households across 10-11 states in Nigeria out of the total 36 states of Nigeria and Abuja.
    Read the news: https://dtm.iom.int/sites/g/files/tmzbdl1461/files/reports/Nigeria%20-20ATLAS%20-20R16202025_.pdf?iframe=true

    Food stuffs are highly expensive in Nigeria and the regime of the current Nigerian government monopolized the few importers that imports grains and fruits to Nigeria, keep majority in abject poverty due to lack of competion. With over 20.12% inflation in August 2025, over 139 million good people of Nigeria has been thrown into abject poverty.

    2.
    Shelter and sleeping (Tents, tarpaulins, and ropes Blankets, sleeping mats, and sleeping bags Bedding sets (sheets, pillows), Cots, non-perishables, water purification tablets, etc.

    Hygiene and health (Soap, shampoo, and toothpaste, Sanitary products and diapers, Toothbrushes and towels, Wet wipes and toilet paper, First-aid kits, Mosquito nets, etc.

    Food and cooking (Non-perishable food items (rice, pasta, tinned food), Kitchen utensils, pots, and pans, sleeping gear, sleeping mats, Tin openers and matches, Water jugs and purification tablets, Fuel for cooking, etc.

    Tools and miscellaneous (Generators, power banks, and flashlights, Batteries, Chainsaws and wheelbarrows, Heavy-duty black bags, Clothes and shoes (new or in very good condition), Children’s toys, etc.

    Financial and other donations (Monetary donations (use official, reputable channels), Gift cards, Volunteer services, etc.

    3. We are working with some group of locals in various capacity. The locals are organizing themselves some local teachers training them with some skills with the support of some foreign foundations. After the training, they supply the skilled teachers to existing schools to improve learning quality for children of the deprived Nigerians. We finance to carry out this mission.

    4. We pays the children school fees on continual unlimited scholarship in the local scheme especially for children’ whose parents were killed by Islamic terrorist extremists. We need finance to carry out this mission.

    5. Before you send any support, please contact our lawyer in Nigeria, Advocate Okonjo Alfred Ikechukwuka Law Firm in his email id: adv@okonjoalfredikechukwuka.com.ng and inform him how much you intend to send. Afterwhich, if you intend to send less than 750 GBP, kindly send it via Money Gram or Ria Money Transfer, to:

    Receiver Name:

    Surname Clark
    names John Colin
    City: London or Manchester
    Country: United Kingdom
    Amount: ???
    Send the payment receipt after making the payment.

    If you intend to send more than 750 pounds or intend to send physical packages, kindly get back to us to supply you with other mode of payment information and the courier receiver information in Nigeria.

    On behalf of Given Life, I would like to express my deepest gratitude for your kindness, generosity, and support.

    Sincerely,
    Laurianne DACOSTA
    (Director)
    Given Life – Manchester
    2 Ashbury Place,
    Manchester, England, M40 8DX,
    United Kingdom
    +44 161 262 1271 (Tel)
    +44 161 262 1272 (Fax)
    https://givenlife.org.uk
    https://find-and-update.company-information.service.gov.uk/company/14279031

  24. (It’s very urgent, therefore we kindly ask you to forward this message to your CEO. If you believe this has been sent to you in error, please ignore it. Thanks)

    Dear CEO,

    This email is from China domain name registration center, which mainly deal with the domain name registration in China. We received an application from Baokang Holdings Ltd requested the “Learnprogramming” as their internet keyword and Chinese (CN) domain names (Learnprogramming.cn, Learnprogramming.com.cn, Learnprogramming.net.cn, Learnprogramming.org.cn) on 25/12/2025. But after checking it, we find this name conflict with your website name or company name. In order to deal with this matter better, it’s necessary to send this message to your company and confirm whether this company is your distributor or business partner in China?

    Best regards

    Adam Liu
    General Manager
    https://www.chinaregistry.org.cn/
    Tel: +86-2161918696 | Fax: +86-2161918697 | Mob: +86-13816428671
    12F Kaike Building, No. 1801 Hongmei Road, Shanghai 200233, China

Leave a Reply to Shanna Edmiston Cancel reply

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

error

Enjoy this blog? Please spread the word :)