package httpcall import ( "bytes" "encoding/json" "fmt" "io/ioutil" "math" "net/http" "git.cryptic.systems/fh-trier/go-flucky/pkg/config" stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types" ) // SendTemperatures remote servers func SendTemperatures(temperatures []*stypes.Temperature, configDir string) error { cnf, err := config.Read(configDir) if err != nil { return 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] } for _, remote := range cnf.Remotes { if remote.Enabled { for _, temperatureBlock := range temperatureBlocks { temperaturesAsBytes, err := json.Marshal(temperatureBlock) if err != nil { 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 nil }