PKGBUILD/pkg/httpcall/remote.go

109 lines
2.6 KiB
Go

package httpcall
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
)
// SyncDevice ..
func SyncDevice(configDir string, force bool) error {
// read config
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// define array of devices
device := types.Device{
DeviceID: cnf.DeviceID,
DeviceLocation: &cnf.DeviceLocation,
DeviceName: &cnf.DeviceName,
DeviceLastContact: time.Now(),
CreationDate: time.Now(),
}
// encode to json
deviceAsBytes, err := json.Marshal(device)
if err != nil {
return err
}
deviceAsReader := bytes.NewReader(deviceAsBytes)
// send array of devices to remote links
for _, remote := range cnf.Remotes {
if !remote.Registered || force {
requestURL := fmt.Sprintf("%v/devices/%v", remote.Address, cnf.DeviceID)
req, err := http.NewRequest("PUT", requestURL, deviceAsReader)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// if resource does not exxists, create a new one
if resp.StatusCode == 404 {
log.Println("test")
requestURL := fmt.Sprintf("%v/devices", remote.Address)
req, err := http.NewRequest("POST", requestURL, deviceAsReader)
if err != nil {
return err
}
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("Can not create a new device on %v - Invalid HTTP-Statuscode, expected 200, got %d - Can not read response body: %v", remote.Name, resp.StatusCode, err)
}
return fmt.Errorf("Can not create a new device on %v - Invalid HTTP-Statuscode, expected 200, got %d: %v", remote.Name, resp.StatusCode, string(b))
}
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Can not update device on %v - Invalid HTTP-Statuscode, expected 200, got %d - Can not read response body: %v", remote.Name, resp.StatusCode, err)
}
return fmt.Errorf("Can not update device on %v - Invalid HTTP-Statuscode, expected 200, got %d: %v", remote.Name, resp.StatusCode, string(b))
}
remote.Registered = true
}
}
if err := config.Write(cnf, configDir); err != nil {
return err
}
return nil
}
// UnregisterDevice ...
func UnregisterDevice(configDir string) error {
return nil
}