loadmaster2k/api/api.go
2020-10-28 11:33:38 +01:00

47 lines
1.1 KiB
Go

package api
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
)
var (
rxLoad = regexp.MustCompile("'width: (?P<load>[0-9]+)%;.* class='status_text'>(?P<status>[^<]*)")
)
func FetchArea(area int) (string, error) {
tUrl := fmt.Sprintf("https://113.webclimber.de/de/trafficlight?callback=WebclimberTrafficlight.insertTrafficlight&key=mu4Gk2NXGBfUU30McdwEkq18SDks2xDB&hid=113&container=trafficlightContainer&type=2&area=%v", area)
tResponse, err := http.Get(tUrl)
if err != nil {
return "", err
}
defer tResponse.Body.Close()
if tResponse.StatusCode / 100 != 2 {
return "", errors.New(fmt.Sprintf("request returned unexpected return code: %v", tResponse.Status))
}
tBody, err := ioutil.ReadAll(tResponse.Body)
if err != nil {
return "", err
}
return string(tBody[:]), nil
}
func ParseAreaStatus(data string) (load int, status string) {
match := rxLoad.FindStringSubmatch(data)
for i, name := range rxLoad.SubexpNames() {
switch name {
case "load":
load, _ = strconv.Atoi(match[i])
case "status":
status = strings.TrimSpace(match[i])
}
}
return
}