PKGBUILD/pkg/config/io.go
Markus Pesch fb8d4dd5eb
fix: new implementation
changes:
- Remove cli
  Some cli commands are not complete tested and are deprecated.

- Daemon
  - Old version has a very bad implementation of how to verify, if the
    device or the sensors are in the database insert. The current
    implementation can be improved but this one is betten then the old
    one.
  - Remove complete the cache store implementation. Use a normal array
    and query the length and capacity to determine how the array cache
    must be cleaned.

- Type
  Remove unused types and functions
2020-05-03 14:09:22 +02:00

62 lines
1.4 KiB
Go

package config
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
)
// Decode a configuration from a reader
func Decode(r io.Reader) (*Config, error) {
cnf := new(Config)
jsonDecoder := json.NewDecoder(r)
if err := jsonDecoder.Decode(&cnf); err != nil {
return nil, fmt.Errorf("Can not unmarshal JSON: %v", err)
}
return cnf, nil
}
// Encode a configuration to a writer
func Encode(cnf *Config, w io.Writer) error {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
err := encoder.Encode(cnf)
if err != nil {
return fmt.Errorf("Error encoding config to json: %v", err)
}
return nil
}
// Read the configuration file
func Read(configFile string) (*Config, error) {
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
}
defer f.Close()
return Decode(f)
}
// Write the configuration into a file, specified by the configuration filepath
func Write(cnf *Config, configFile string) error {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
configDir := filepath.Dir(configFile)
err := os.MkdirAll(configDir, os.ModeDir)
if err != nil {
return fmt.Errorf("Failed to create config directory %v: %v", configDir, err)
}
}
f, err := os.Create(configFile)
if err != nil {
return fmt.Errorf("Failed not create config file %v: %v", configFile, err)
}
defer f.Close()
return Encode(cnf, f)
}