fix: splited temperatures

Changes:
- Split temperatures from log file into blocks.
  Every block has a size of 500 entries. Every block would be send to
  the remote host
This commit is contained in:
2018-12-07 22:50:28 +01:00
parent 81600154f0
commit 500d1a5823
8 changed files with 175 additions and 102 deletions

View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
@ -20,34 +21,54 @@ func SendTemperatures(temperatures []*stypes.Temperature, configDir string) erro
return err
}
temperaturesAsBytes, err := json.Marshal(temperatures)
if err != nil {
return fmt.Errorf("Can not marshal temperatures to JSON: %v", err)
// split temperatures in blocks to reduce server data size in single request
blockSize := 500
temperatureBlocks := make(map[int][]*stypes.Temperature)
length := int(math.Ceil(float64(len(temperatures)) / float64(blockSize)))
for i := 0; i < length; i++ {
start := i * blockSize
end := (i + 1) * blockSize
if end > len(temperatures) {
end = len(temperatures)
}
temperatureBlocks[i] = temperatures[start:end]
}
temperaturesAsReader := bytes.NewReader(temperaturesAsBytes)
for _, remote := range cnf.Remotes {
if remote.Enabled {
requestURL := fmt.Sprintf("%s%s", remote.Address, "/temperatures")
req, err := http.NewRequest("POST", requestURL, temperaturesAsReader)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
for _, temperatureBlock := range temperatureBlocks {
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, err := ioutil.ReadAll(resp.Body)
temperaturesAsBytes, err := json.Marshal(temperatureBlock)
if err != nil {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d - can not read response body: %v", resp.StatusCode, err)
return fmt.Errorf("Can not marshal temperatures to JSON: %v", err)
}
temperaturesAsReader := bytes.NewReader(temperaturesAsBytes)
requestURL := fmt.Sprintf("%s%s", remote.Address, "/temperatures")
req, err := http.NewRequest("POST", requestURL, temperaturesAsReader)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d - can not read response body: %v", resp.StatusCode, err)
}
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d: %v", resp.StatusCode, string(b))
}
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d: %v", resp.StatusCode, string(b))
}
}
}