2
3

More than 5 years have passed since last update.

Goでopenweatherapiを使って東京の天気を取得する

Posted at

Goの練習として、openweatherapiというフリーで使える天気情報取得サービスのAPIを利用するものを作ってみた。
また、単純にリクエストを投げて結果を表示するだけでも良かったが、structに格納してから改めて文字列として出力するようにしてみた。

技術要件

  • Go 1.11.2

事前準備

openweatherapiのAPIキーが必要になるので、アカウント登録をしてこれを取得する。
無料だとリクエスト数や利用できるAPIに制限がかかるが、今回は特に問題はない。

実装

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
)

const OpenWeatherApiKey = "YOUR_OPENWEATHERAPIKEY_HERE"

type Coord struct {
    Lon float32
    Lat float32
}

type Weather struct {
    Id int
    Main string
    Description string
    Icon string
}

type Main struct {
    Temp float32
    Pressure int
    Humidity int
    TempMin float32
    TempMax float32
}

type Wind struct {
    Speed float32
    Deg int
}

type Clouds struct {
    All int
}

type Sys struct {
    Type int
    Id int
    Message float32
    Country string
    Sunrise int
    Sunset int
}

type Response struct {
    Coord Coord
    Weather []Weather
    Base string
    Main Main
    Visibility int
    Wind Wind
    Clouds Clouds
    Dt int
    Sys Sys
    Id int
    Name string
    Cod int
}

func main() {
    values := url.Values{}
    values.Add("q", "Tokyo")
    values.Add("APPID", OpenWeatherApiKey)

    req, err := http.NewRequest("GET", "https://api.openweathermap.org/data/2.5/weather", nil)
    if err != nil {
        panic(err)
    }

    req.URL.RawQuery = values.Encode()
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    defer res.Body.Close()

    response := Response{}
    err = json.NewDecoder(res.Body).Decode(&response)
    if err != nil {
        panic(err)
    }
    result, err := json.Marshal(response)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(result))
}

簡単に使用したAPIの説明をすると、今回はweatherという機能を使用している。
これはqに地名を指定することで、その場所の天気情報を取得することができる。
APIキーはAPPIDとして指定する。

これを実行すれば東京の天気が取得できる。

> go run main.go
{"Coord":{"Lon":139.76,"Lat":35.68},"Weather":[{"Id":803,"Main":"Clouds","Description":"broken clouds","Icon":"04n"}],"Base":"stations","Main":{"Temp":279.18,"Pressure":1015,"Humidity":57,"TempMin":0,"TempMax":0},"Visibility":10000,"Wind":{"Speed":7.2,"Deg":340},"Clouds":{"All":75},"Dt":1544281200,"Sys":{"Type":1,"Id":8074,"Message":0.0043,"Country":"JP","Sunrise":1544218696,"Sunset":1544254049},"Id":1850147,"Name":"Tokyo","Cod":200}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3