Timeout after 10 seconds on FetchDepartures

Also apply gofmt
This commit is contained in:
Paul Brinkmeier 2024-07-17 07:35:11 +02:00
parent 330e5923af
commit 3fe42e1ff0
2 changed files with 102 additions and 100 deletions

View File

@ -2,7 +2,7 @@
## TODO
- [ ] Use timeout for fetching departures
- [x] Use timeout for fetching departures
- [ ] Write ESP8266 client
- [ ] Add basic auth
- [ ] Create Nix package

10
main.go
View File

@ -7,6 +7,7 @@ import "net/http"
import "net/url"
import "slices"
import "strconv"
import "time"
type DMResponse struct {
Departures []DMDeparture `json:"departureList"`
@ -38,7 +39,6 @@ type DMDateTime struct {
Minute string `json:"minute"`
}
// TODO: Use different client (with timeout)
func FetchDepartures(stopId string) (*DMResponse, error) {
// Create request object
req, err := http.NewRequest("GET", "https://www.vrn.de/mngvrn/XML_DM_REQUEST", nil)
@ -61,8 +61,11 @@ func FetchDepartures(stopId string) (*DMResponse, error) {
query.Set("useRealtime", "1")
req.URL.RawQuery = query.Encode()
// Send the request
res, err := http.DefaultClient.Do(req)
// Send the request, wait max 10 seconds
client := http.Client{
Timeout: 10 * time.Second,
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
@ -92,7 +95,6 @@ func main() {
platform = &query["platform"][0]
}
ds, err := FetchDepartures(stopId)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)