package logs import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types" "git.cryptic.systems/fh-trier/go-flucky/pkg/types" ) // AppendTemperature write a given array of temperatures to a logfile func AppendTemperature(temperatures []*stypes.Temperature, cnf *types.Config) error { tLog, err := ReadTemperatures(cnf.TemperatureLogfile) if err != nil { return err } tLog = append(tLog, temperatures...) err = WriteTemperatures(tLog, cnf.TemperatureLogfile) if err != nil { return err } return nil } // FlushTemperatures ... func FlushTemperatures(logFile string) error { if err := ioutil.WriteFile(logFile, []byte(""), 0644); err != nil { return err } return nil } // ReadTemperatures ... func ReadTemperatures(logFile string) ([]*stypes.Temperature, error) { logPath := filepath.Dir(logFile) // create log dir if not exist if _, err := os.Stat(logFile); os.IsNotExist(err) { if _, err := os.Stat(logPath); os.IsNotExist(err) { err := os.MkdirAll(logPath, os.ModePerm) if err != nil { return nil, fmt.Errorf("Can not create directory: %v", err) } } if err := FlushTemperatures(logFile); err != nil { return nil, err } } // open config file jsonFile, err := os.Open(logFile) if err != nil { return nil, fmt.Errorf("Can not open file %v: %v", logFile, err) } defer jsonFile.Close() bytes, err := ioutil.ReadAll(jsonFile) if err != nil { return nil, fmt.Errorf("Can not read jsonfile %v: %v", logFile, err) } temperatures := []*stypes.Temperature{} json.Unmarshal(bytes, &temperatures) return temperatures, nil } // WriteTemperatures ... func WriteTemperatures(temperatures []*stypes.Temperature, logFile string) error { bytes, err := json.Marshal(temperatures) if err != nil { return err } if err := ioutil.WriteFile(logFile, bytes, 0644); err != nil { return err } return nil }