spacepanel_aggregator/poll.go

73 lines
1.1 KiB
Go

package main
import (
"crypto/tls"
"errors"
"io/ioutil"
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/valyala/fastjson"
)
const (
SleepTime = time.Minute
)
var (
insecureTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: insecureTransport,
}
)
func StartPollWorker(space *Space) {
for {
state, err := requestSpaceState(space.URL)
if err != nil {
logrus.Errorf("URL: %s, Err: %v", space.URL, err)
}
space.State = state
time.Sleep(SleepTime)
}
}
func requestSpaceState(url string) (State, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return Unknown, err
}
resp, err := client.Do(req)
if err != nil {
return Unknown, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return Unknown, err
}
value, err := fastjson.ParseBytes(data)
if err != nil {
return Unknown, err
}
if !value.Exists("state", "open") {
return Unknown, errors.New("no space state existing")
}
state := value.GetBool("state", "open")
if state {
return Open, nil
}
return Close, nil
}