-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_wrapper.go
405 lines (368 loc) · 14.4 KB
/
api_wrapper.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package govvs
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
)
const (
baseURLJourney = "https://www3.vvs.de/mngvvs/XML_TRIP_REQUEST2"
baseURLWidgetDM = "http://www3.vvs.de/vvs/widget/XML_DM_REQUEST"
)
const (
defaultDepartureLimit = 100
defaultArrivalLimit = 100
defaultJourneyLimit = 100
)
// GetJourney initiates a request to retrieve journey information between two locations at a specified time.
// It uses the VVS (Verkehrs- und Tarifverbund Stuttgart) API to calculate routes, taking into account various transport options and preferences.
//
// Parameters:
// - r JourneyRequest: Struct containing the essential information for the journey request.
// - OrigId: The ID or code representing the origin location for the journey. This should be in the format recognized by the VVS API, e.g., "de:08111:2599".
// - DstId: The ID or code representing the destination location for the journey, formatted similarly to OrigId.
// - TimeAt: Pointer to a time.Time object specifying the desired departure or arrival time for the journey.
// - Limit: Pointer to an integer specifying the maximum number of journey options to return. If nil, a default value defined by the API will be used.
// - LangCode: Pointer to a string specifying the language code for the response, e.g., "de" for German. If nil, the API's default language will be used.
//
// - reqParams ...ReqParam: An optional slice of ReqParam structs allowing for additional parameters to be specified for the journey request. These can include:
// - Name: The name of the parameter, matching the constant names defined for VVS API parameters, e.g., ParamCalcOneDirection.
// - Value: The value of the parameter, as a string, e.g., "1" for true or specific values like "EPSG:4326" for coordinate formats.
//
// The function supports various optional parameters that can be used to refine the journey search, including but not limited to:
// - ChangeSpeed: Adjusts the assumed speed of changing between transport modes.
// - RouteType: Determines the criteria for route selection, such as "LEASTTIME" for the shortest overall journey time.
// - UseRealtime: Specifies whether to include real-time data in the journey calculation.
//
// Returns:
// - *JourneyResponse: A pointer to a JourneyResponse struct containing the journey options found based on the request parameters. This includes detailed route information, timings, and any applicable fare information.
// - error: An error object that will be non-nil if there was an issue processing the request or communicating with the VVS API.
//
// Example usage:
//
// journeyReq := JourneyRequest{
// OrigId: "de:08111:2599",
// DstId: "de:08111:6075",
// TimeAt: time.Now(),
// Limit: 10,
// LangCode: "de",
// }
//
// journeyResp, err := GetJourney(journeyReq, ReqParam{Name: ParamRouteType, Value: "leasttime"})
//
// if err != nil {
// // Handle error
// }
//
// // Process journeyResp
func GetJourney(r JourneyRequest, reqParams ...ReqParam) (*JourneyResponse, error) {
// Prepare query parameters
params := url.Values{}
// set default params
setDefaultJourneyReqParams(params)
// Set dynamic values separately
limit := defaultJourneyLimit
if r.Limit != nil {
limit = *r.Limit
}
limitParam := strconv.Itoa(limit)
timeAt := time.Now()
if r.TimeAt != nil {
timeAt = *r.TimeAt
}
orig := r.OrigId
dst := r.DstId
params.Set(ParamItdDate, timeAt.Format("20060102"))
params.Set(ParamItdTime, timeAt.Format("1504"))
params.Set(ParamNameDestination, dst)
params.Set(ParamNameOrigin, orig)
params.Set(ParamLimit, limitParam)
// override optional params6
overrideReqParams(params, reqParams...)
// Build the URL with encoded query parameters
url := baseURLJourney + "?" + params.Encode()
// Make the GET request
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error making GET request: %v\n", err)
return nil, err
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return nil, err
}
// Unmarshal the JSON response into the JourneyResponse struct
var journeyResponse JourneyResponse
err = json.Unmarshal(body, &journeyResponse)
if err != nil {
fmt.Printf("Error unmarshalling JSON: %v\n", err)
return nil, err
}
// Return the populated JourneyResponse struct
return &journeyResponse, nil
}
// GetArrivals sends a request to retrieve arrival information for a specified station or location.
// The function takes an ArrivalRequest struct containing essential request parameters and
// a variable number of ReqParam structs to specify additional request options.
//
// Parameters:
// - r ArrivalRequest: A struct containing the base request parameters such as station ID and request time.
//
// - OrigId (string): The origin station identifier. Not used in this context but can be set for consistency.
//
// - DstId (string): The destination station identifier. This is typically the station ID for which arrivals are requested.
//
// - TimeAt (*time.Time): The specific date and time for which arrival information is requested. If nil, current time is assumed.
//
// - Limit (*int): The maximum number of arrival entries to retrieve. If nil, a default limit is applied.
//
// - LangCode (*string): The language code for the response (e.g., "de" for German). If nil, a default language is used.
//
// - reqParams ...ReqParam: Optional parameters to further customize the request. Each ReqParam consists of a Name and Value.
// Supported optional parameters (refer to constants for parameter names):
//
// - ParamLocationServerActive: Activates the location server for processing the request.
//
// - ParamLsShowTrainsExplicit: Specifies whether trains should be shown explicitly in the response.
//
// - ParamStateless: Indicates if the request should be processed without maintaining state.
//
// - ParamLanguage: Sets the language of the response.
//
// - ParamSpEncId: Security parameter, typically "0".
//
// - ParamAnySigWhenPerfectNoOtherMatches: Used to refine search results.
//
// - ParamLimit: Controls the maximum number of results returned.
//
// - ParamDepArr: Indicates whether departure or arrival times are requested ("arrival" for arrivals).
//
// - ParamTypeDm: Specifies the type of data management request.
//
// - ParamAnyObjFilterDm: Filters objects based on specified criteria.
//
// - ParamDeleteAssignedStops: Indicates whether assigned stops should be removed from the response.
//
// - ParamNameDm: The name or ID of the station for which arrivals are being requested.
//
// - ParamMode: Specifies the mode of transport.
//
// - ParamDmLineSelectionAll: Determines if all lines should be selected in the request.
//
// - ParamUseRealtime: Specifies whether real-time data should be used.
//
// - ParamOutputFormat: Defines the output format of the response.
//
// - ParamCoordOutputFormat: Sets the coordinate format for the response.
//
// - ParamItdDateTimeDepArr: Specifies the desired time for departure or arrival.
//
// - Additional parameters related to date and time of the request: ParamItdDateYear, ParamItdDateMonth, ParamItdDateDay, ParamItdTimeHour, ParamItdTimeMinute.
//
// Returns:
// - (*ArrivalResponse, error): A pointer to an ArrivalResponse struct containing the requested arrival information, or an error if the request fails.
//
// Example usage:
// response, err := GetArrivals(ArrivalRequest{DstId: "stationID", TimeAt: &time.Now()}, ReqParam{Name: ParamLimit, Value: "5"})
//
// if err != nil {
// // handle error
// }
//
// // process response
func GetArrivals(r ArrivalRequest, reqParams ...ReqParam) (*ArrivalResponse, error) {
// Prepare query parameters
params := url.Values{}
setDefaultArrivalReqParams(params)
limit := defaultArrivalLimit
if r.Limit != nil {
limit = *r.Limit
}
limitParam := strconv.Itoa(limit)
timeAt := time.Now()
if r.TimeAt != nil {
timeAt = *r.TimeAt
}
year := timeAt.Format("2006")
month := timeAt.Format("01")
day := timeAt.Format("02")
hour := timeAt.Format("15")
minute := timeAt.Format("04")
stationId := r.StationId
params.Set(ParamItdDateYear, year)
params.Set(ParamItdDateMonth, month)
params.Set(ParamItdDateDay, day)
params.Set(ParamItdTimeHour, hour)
params.Set(ParamItdTimeMinute, minute)
params.Set(ParamNameDm, stationId)
params.Set(ParamLimit, limitParam)
overrideReqParams(params, reqParams...)
// Build the URL with encoded query parameters
url := baseURLWidgetDM + "?" + params.Encode()
// Make the GET request
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error making GET request: %v\n", err)
return nil, err
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return nil, err
}
// Unmarshal the JSON response into the ArrivalResponse struct
var arrivalResponse ArrivalResponse
err = json.Unmarshal(body, &arrivalResponse)
if err != nil {
fmt.Printf("Error unmarshalling JSON: %v\n", err)
return nil, err
}
// Return the populated ArrivalResponse struct
return &arrivalResponse, nil
}
// GetDepartures sends a request to retrieve departure information for a specified station or location.
// The function takes a DepartureRequest struct containing essential request parameters and
// a variable number of ReqParam structs to specify additional request options.
//
// Parameters:
// - r DepartureRequest: A struct containing the base request parameters such as station ID and request time.
//
// - OrigId (string): The origin station identifier. In the context of departures, this is the station ID from which departures are requested.
//
// - DstId (string): The destination station identifier. Not typically used for departure requests but can be set for API consistency.
//
// - TimeAt (*time.Time): The specific date and time for which departure information is requested. If nil, the current time is assumed.
//
// - Limit (*int): The maximum number of departure entries to retrieve. If nil, a default limit is applied.
//
// - LangCode (*string): The language code for the response (e.g., "de" for German). If nil, a default language is used.
//
// - reqParams ...ReqParam: Optional parameters to further customize the request. Each ReqParam consists of a Name and Value.
// Supported optional parameters (refer to constants for parameter names):
//
// - ParamLocationServerActive: Activates the location server for processing the request.
//
// - ParamLsShowTrainsExplicit: Specifies whether trains should be shown explicitly in the response.
//
// - ParamStateless: Indicates if the request should be processed without maintaining state.
//
// - ParamLanguage: Sets the language of the response.
//
// - ParamSpEncId: Security parameter, typically "0".
//
// - ParamAnySigWhenPerfectNoOtherMatches: Used to refine search results.
//
// - ParamLimit: Controls the maximum number of results returned.
//
// - ParamDepArr: Indicates whether departure or arrival times are requested ("departure" for departures).
//
// - ParamTypeDm: Specifies the type of data management request.
//
// - ParamAnyObjFilterDm: Filters objects based on specified criteria.
//
// - ParamDeleteAssignedStops: Indicates whether assigned stops should be removed from the response.
//
// - ParamNameDm: The name or ID of the station for which departures are being requested.
//
// - ParamMode: Specifies the mode of transport.
//
// - ParamDmLineSelectionAll: Determines if all lines should be selected in the request.
//
// - ParamUseRealtime: Specifies whether real-time data should be used.
//
// - ParamOutputFormat: Defines the output format of the response.
//
// - ParamCoordOutputFormat: Sets the coordinate format for the response.
//
// - Additional parameters related to date and time of the request: ParamItdDateYear, ParamItdDateMonth, ParamItdDateDay, ParamItdTimeHour, ParamItdTimeMinute.
//
// Returns:
// - (*DepartureResponse, error): A pointer to a DepartureResponse struct containing the requested departure information, or an error if the request fails.
//
// Example usage:
// response, err := GetDepartures(DepartureRequest{OrigId: "stationID", TimeAt: &time.Now()}, ReqParam{Name: ParamLimit, Value: "10"})
//
// if err != nil {
// // handle error
// }
//
// // process response
func GetDepartures(r DepartureRequest, reqParams ...ReqParam) (*DepartureResponse, error) {
// Assemble the query parameters
params := url.Values{}
setDefaultDepartureReqParams(params)
limit := defaultDepartureLimit
if r.Limit != nil {
limit = *r.Limit
}
limitParam := strconv.Itoa(limit)
timeAt := time.Now()
if r.TimeAt != nil {
timeAt = *r.TimeAt
}
year := timeAt.Format("2006")
month := timeAt.Format("01")
day := timeAt.Format("02")
hour := timeAt.Format("15")
minute := timeAt.Format("04")
stationId := r.StationId
params.Set(ParamItdDateYear, year)
params.Set(ParamItdDateMonth, month)
params.Set(ParamItdDateDay, day)
params.Set(ParamItdTimeHour, hour)
params.Set(ParamItdTimeMinute, minute)
params.Set(ParamNameDm, stationId)
params.Set(ParamLimit, limitParam)
overrideReqParams(params, reqParams...)
// Build the complete URL with the encoded query parameters
fullURL := baseURLWidgetDM + "?" + params.Encode()
// Perform the GET request
resp, err := http.Get(fullURL)
if err != nil {
fmt.Println("Error making GET request:", err)
return nil, err
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return nil, err
}
// Unmarshal the JSON response into the DepartureResponse struct
var departureResponse DepartureResponse
err = json.Unmarshal(body, &departureResponse)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return nil, err
}
return &departureResponse, nil
}
func overrideReqParams(urlParams url.Values, params ...ReqParam) {
for _, param := range params {
urlParams.Set(param.Name, param.Value)
}
}
func setDefaultArrivalReqParams(urlParams url.Values) {
for param, defaultValue := range defaultArrivalParams {
urlParams.Set(param, defaultValue)
}
}
func setDefaultDepartureReqParams(urlParams url.Values) {
for param, defaultValue := range defaultDepartureParams {
urlParams.Set(param, defaultValue)
}
}
func setDefaultJourneyReqParams(urlParams url.Values) {
for param, defaultValue := range defaultJourneyParams {
urlParams.Set(param, defaultValue)
}
}