71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
package db
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"os"
|
|
|
|
"git.stinnesbeck.com/go/jynx/backend/common"
|
|
"git.stinnesbeck.com/go/jynx/backend/hetzner"
|
|
)
|
|
|
|
func Read() ([]common.Server, error) {
|
|
// open file for reading, create it when necessary
|
|
f, err := os.OpenFile("db.json", os.O_RDONLY|os.O_CREATE, os.ModePerm)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
servers, err := hetzner.ListServers()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// close file when we are done
|
|
defer f.Close()
|
|
|
|
// read file as byte array
|
|
b, err := io.ReadAll(f)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if len(b) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
// parse byte array to []common.Server
|
|
var serversFromDB []common.Server
|
|
if err := json.Unmarshal(b, &serversFromDB); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// merge servers from db and hcloud
|
|
servers = append(servers, serversFromDB...)
|
|
|
|
// return read in servers
|
|
return servers, nil
|
|
}
|
|
|
|
func Save(servers []common.Server) error {
|
|
// open file with provided flags, create it when necessary
|
|
f, err := os.OpenFile("db.json", os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// close file when we are done
|
|
defer f.Close()
|
|
|
|
// Marshal data as JSON and put into byte array
|
|
b, err := json.MarshalIndent(servers, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// write byte array to file
|
|
_, err = f.Write(b)
|
|
|
|
return err
|
|
}
|