Help us understand the problem. What is going on with this article?

【Go】OpenWeatherMap APIを使用して現在の天気情報を取得する

はじめに

OpenWeatherMap APIの基本的な使い方に関してはこちらの記事を参照

サンプルコード

各フィールドの正確なデータ型(int, float64等)はわからなかったので、ここのJSONレスポンス例の値を参考に指定していますが、間違っている可能性もあります。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "time"
)

type OpenWeatherMapAPIResponse struct {
    Main    Main      `json:"main"`
    Weather []Weather `json:"weather"`
    Coord   Coord     `json:"coord"`
    Wind    Wind      `json:"wind"`
    Dt      int64     `json:"dt"`
}

type Main struct {
    Temp     float64 `json:"temp"`
    TempMin  float64 `json:"temp_min"`
    TempMax  float64 `json:"temp_max"`
    Pressuer int     `json:"pressure"`
    Humidity int     `json:"humidity"`
}

type Coord struct {
    Lon float64 `json:"lon"`
    Lat float64 `json:"lat"`
}

type Weather struct {
    Main        string `json:"main"`
    Description string `json:"description"`
    Icon        string `json:"icon"`
}

type Wind struct {
    Speed float64 `json:"speed"`
    Deg   int     `json:"deg"`
}

func main() {
    token := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"                   // APIトークン
    city := "Tokyo,jp"                                            // 東京を指定
    endPoint := "https://api.openweathermap.org/data/2.5/weather" // APIのエンドポイント

    // パラメータを設定
    values := url.Values{}
    values.Set("q", city)
    values.Set("APPID", token)

    // リクエストを投げる
    res, err := http.Get(endPoint + "?" + values.Encode())
    if err != nil {
        panic(err)
    }
    defer res.Body.Close()

    // レスポンスを読み取り
    bytes, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(bytes))
    // => {"coord":{"lon":139.76,"lat":35.68},"weather":[{"id":803,"main":"Clouds","description":"broken clo
    //    uds","icon":"04n"}],"base":"stations","main":{"temp":297.16,"pressure":1004,"humidity":94,"temp_mi
    //    n":295.93,"temp_max":298.15},"visibility":10000,"wind":{"speed":2.6,"deg":70},"clouds":{"all":75},
    //    "dt":1568645761,"sys":{"type":1,"id":8074,"message":0.0067,"country":"JP","sunrise":1568665471,"su
    //    nset":1568710031},"timezone":32400,"id":1850147,"name":"Tokyo","cod":200}

    // JSONパース
    var apiRes OpenWeatherMapAPIResponse
    if err := json.Unmarshal(bytes, &apiRes); err != nil {
        panic(err)
    }

    fmt.Printf("時刻:     %s\n", time.Unix(apiRes.Dt, 0))
    fmt.Printf("天気:     %s\n", apiRes.Weather[0].Main)
    fmt.Printf("アイコン: https://openweathermap.org/img/wn/%s@2x.png\n", apiRes.Weather[0].Icon)
    fmt.Printf("説明:     %s\n", apiRes.Weather[0].Description)
    fmt.Printf("緯度:     %f\n", apiRes.Coord.Lat)
    fmt.Printf("経度:     %f\n", apiRes.Coord.Lon)
    fmt.Printf("気温:     %f\n", apiRes.Main.Temp) // ケルビンで取得される
    fmt.Printf("最高気温: %f\n", apiRes.Main.TempMax)
    fmt.Printf("最低気温: %f\n", apiRes.Main.TempMin)
    fmt.Printf("気圧:     %d\n", apiRes.Main.Pressuer)
    fmt.Printf("湿度:     %d\n", apiRes.Main.Humidity)
    fmt.Printf("風速:     %f\n", apiRes.Wind.Speed)
    fmt.Printf("風向き:   %d\n", apiRes.Wind.Deg)

    // => 時刻:     2019-09-16 23:56:01 +0900 JST
    //    天気:     Clouds
    //    アイコン: http://openweathermap.org/img/wn/04n@2x.png
    //    説明:     broken clouds
    //    緯度:     35.680000
    //    経度:     139.760000
    //    気温:     297.160000
    //    最高気温: 298.150000
    //    最低気温: 295.930000
    //    気圧:     1004
    //    湿度:     94
    //    風速:     2.600000
    //    風向き:   70
}

参考

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away