-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetStationList.go
49 lines (45 loc) · 1.19 KB
/
getStationList.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"encoding/json"
"errors"
"io"
"michikusa_back/types"
"net/http"
"net/url"
"strconv"
)
// 最寄駅を通る路線の駅一覧を取得する関数
// 最寄り駅はフィルタされる
func GetStationList(nearestStation types.OdptStation, odptAPIKey string) ([]types.OdptStation, error) {
baseURL := "https://api.odpt.org/api/v4/odpt:Station"
u, _ := url.Parse(baseURL)
q := u.Query()
q.Set("odpt:railway", nearestStation.Railway)
q.Set("acl:consumerKey", odptAPIKey)
u.RawQuery = q.Encode()
req, _ := http.NewRequest("GET", u.String(), nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New("failed to get station list. status code: " + strconv.Itoa(resp.StatusCode))
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var stations []types.OdptStation
if err := json.Unmarshal(body, &stations); err != nil {
return nil, err
}
// 最寄り駅をフィルタする
for i, station := range stations {
if station.ID == nearestStation.ID {
stations = append(stations[:i], stations[i+1:]...)
break
}
}
return stations, nil
}