netbird/util/file.go
Mikhail Bragin 4587f7686e
feature: basic management service implementation (#44)
* feat: basic management service implementation [FAILING TESTS]

* test: fix healthcheck test

* test: #39 add peer registration endpoint test

* feat: #39 add setup key handling

* feat: #39 add peer management store persistence

* refactor: extract config read/write to the utility package

* refactor: move file contents copy to the utility package

* refactor: use Accounts instead of Users in the Store

* feature: add management server Docker file

* refactor: introduce datadir instead of config

* chore: use filepath.Join to concat filepaths instead of string concat

* refactor: move stop channel to the root

* refactor: move stop channel to the root

* review: fix PR review notes

Co-authored-by: braginini <hello@wiretrustee.com>
2021-07-17 14:38:59 +02:00

80 lines
1.3 KiB
Go

package util
import (
"encoding/json"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// WriteJson writes JSON config object to a file creating parent directories if required
// The output JSON is pretty-formatted
func WriteJson(file string, obj interface{}) error {
configDir := filepath.Dir(file)
err := os.MkdirAll(configDir, 0750)
if err != nil {
return err
}
// make it pretty
bs, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(file, bs, 0600)
if err != nil {
return err
}
return nil
}
// ReadJson reads JSON config file and maps to a provided interface
func ReadJson(file string, res interface{}) (interface{}, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
bs, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
err = json.Unmarshal(bs, &res)
if err != nil {
return nil, err
}
return res, nil
}
// CopyFileContents copies contents of the given src file to the dst file
func CopyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cErr := out.Close()
if err == nil {
err = cErr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}