1. ソースコード
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
const (
ENDPOINT = "https://api.tokyometroapp.jp/api/v2/datapoints"
CONSUMER_KEY = "CONSUMER_KEY"
)
type TrainLocation struct {
Context string `json:"@context"`
Id string `json:"@id"`
Type string `json:"@type"`
SameAs string `json:"owl:sameAs"`
TrainNumber string `json:"odpt:trainNumber"`
TrainType string `json:"odpt:trainType"`
Date time.Time `json:"dct:date"`
Valid time.Time `json:"dct:valid"`
Frequency uint64 `json:"odpt:frequency"`
Railway string `json:"odpt:railway"`
TrainOwner string `json:"odpt:trainOwner"`
RailDirection string `json:"odpt:RailDirection"`
Delay uint64 `json:"odpt:delay"`
StartingStation string `json:"odpt:startingStation"`
TerminalStation string `json:"odpt:terminalStation"`
FromStation string `json:"odpt:fromStation"`
ToStation string `json:"odpt:toStation"`
}
type trainLocations []TrainLocation
func main() {
// URL生成
queryMap := map[string]string{
"rdf:type": "odpt:Train",
"acl:consumerKey": CONSUMER_KEY,
"odpt:railDirection": "odpt.RailDirection:TokyoMetro.Shibuya",
}
url := fmt.Sprintf("%s?%s", ENDPOINT, buildQuery(queryMap))
// レスポンス取得
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// JSONデコード
var trains trainLocations
if err := json.Unmarshal(body, &trains); err != nil {
log.Fatal(err)
}
// 取得したデータを表示する
fmt.Println("")
fmt.Println("Direction : Shibuya")
fmt.Println("")
for _, train := range trains {
sameAs := train.SameAs
sameAs = strings.Replace(sameAs, "odpt.Train:TokyoMetro.", "", -1)
from := train.FromStation
from = strings.Replace(from, "odpt.Station:TokyoMetro.", "", -1)
to := train.ToStation
// train.ToStationがない(停車中の時)
if len(to) == 0 {
fmt.Printf("%s | At:%s\n", sameAs, from)
}
}
}
func buildQuery(queryMap map[string]string) string {
queries := make([]string, 0)
for k, v := range queryMap {
query := fmt.Sprintf("%s=%s", k, v)
queries = append(queries, query)
}
return strings.Join(queries, "&")
}
2. 実行結果例
Direction : Shibuya
Hanzomon.B1083S | At:Hanzomon.KiyosumiShirakawa
Hanzomon.B0963S | At:Hanzomon.Shibuya
Ginza.A1049 | At:Ginza.Asakusa
Ginza.A1043 | At:Ginza.Tawaramachi
Ginza.A1053 | At:Ginza.Ueno
Ginza.A1011 | At:Ginza.UenoHirokoji
Ginza.A1017 | At:Ginza.Kanda
Ginza.A1065 | At:Ginza.Nihombashi
Ginza.A1037 | At:Ginza.Shimbashi
Ginza.A1013 | At:Ginza.AkasakaMitsuke
Ginza.A1031 | At:Ginza.OmoteSando
Ginza.A0929 | At:Ginza.Shibuya
Fukutoshin.A0921T | At:Fukutoshin.KotakeMukaihara
3. 参考
https://developer.tokyometroapp.jp/documents/railwayhttps://qiita.com/nayuneko/items/ca2651e3a613c8e3256a