概要
Random User Generator というサイトで、ランダムなユーザー情報を取得できる JSON の API を提供している。
早速使ってみる。
API はこの URL (https://randomuser.me/api) からアクセスできる。
Unmarshal したい JSON の構造を調べる
{
"location": {
"street": "9278 new road",
"city": "kilcoole",
"state": "waterford",
"postcode": "93027",
"coordinates": {
"latitude": "20.9267",
"longitude": "-7.9310"
}
}
}
この構造は、こう書ける
type Location struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Postcode string `json:"postcode"`
Coordinates struct {
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
} `json:"coordinates"`
}
前もって構造体を定義していなくても、type
配下で別の type
を直接書くこともできる。
その場合の、json タグは、{}
で閉じた後であることに注意。
コード
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type RespData struct {
Results []Result `json:"results"`
Info Info `json:"info"`
}
type Result struct {
Gender string `json:"gender"`
Name Name `json:"name"`
Location Location `json:"location"`
Email string `json:"email"`
}
type Name struct {
Title string `json:"title"`
First string `json:"first"`
Last string `json:"last"`
}
type Location struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Postcode string `json:"postcode"`
Coordinates struct {
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
} `json:"coordinates"`
}
type Info struct {
Seed string `json:"seed"`
Results int `json:"results"`
Page int `json:"page"`
Version string `json:"version"`
}
func main() {
url := "https://randomuser.me/api/"
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error")
}
defer resp.Body.Close()
// resp: Pinter to type Response
// fmt.Println("Status", resp.Status)
// fmt.Println("StatusCode", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
var data RespData
_ = json.Unmarshal(body, &data)
fmt.Printf("%v\n", data.Results[0])
fmt.Printf("%v\n", data.Info)
}