Last active
August 28, 2018 14:25
-
-
Save aikyo02/37fa113f9d48f74c7d763584b2d0ce13 to your computer and use it in GitHub Desktop.
APIを叩いてJSONにするところまで
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"io/ioutil" | |
"encoding/json" | |
) | |
const API_KEY = "xxxxxxxxxxxxxxx" | |
const BASE_URL = "http://api.openweathermap.org/data/2.5/weather" | |
type Weather struct { | |
Id int `json:"id"` | |
Main string `json:"main"` | |
Description string `json:"description"` | |
} | |
type WeatherJson struct { | |
Weather []Weather `json:"weather"` | |
} | |
func main() { | |
url := BASE_URL + "?"+ "q=tokyo&units=metric" + "&appid=" + API_KEY | |
resp, err := http.Get(url) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer resp.Body.Close() | |
byteArray, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
weatherJson := new(WeatherJson) | |
if err := json.Unmarshal(byteArray, weatherJson); err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(weatherJson.Weather[0].Id) // ex. 803 | |
fmt.Println(weatherJson.Weather[0].Main) // ex. Clouds | |
fmt.Println(weatherJson.Weather[0].Description) // ex. broken clouds | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment