Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improved save function. Old one is stale. #64

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
.idea
48 changes: 48 additions & 0 deletions configor.go
@@ -1,10 +1,16 @@
package configor

import (
"encoding/json"
"errors"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
)

Expand Down Expand Up @@ -110,6 +116,48 @@ func (configor *Configor) Load(config interface{}, files ...string) (err error)
return
}

// Save will save the configurations to a file name you provide
func Save(config interface{}, filename string) error {
var js []byte
var err error
var filePerm os.FileMode = 0664
var folderPerm os.FileMode = 0775

// get directory
path, err := filepath.Abs(filepath.Dir(filename))
if err != nil {
return err
}

// create it if not exists
err = os.MkdirAll(path, folderPerm)
if err != nil {
return err
}

// create the config file if doesnt exist already
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, filePerm)
if err != nil {
return err
}
file.Close()

switch {
case strings.HasSuffix(filename, ".yaml") || strings.HasSuffix(filename, ".yml"):
js, err = yaml.Marshal(&config)
case strings.HasSuffix(filename, ".json"):
js, err = json.Marshal(&config)
default:
return errors.New("unknown file type")
}

if err != nil {
return err
}

return ioutil.WriteFile(filename, js, filePerm)
}

// ENV return environment
func ENV() string {
return New(nil).GetEnvironment()
Expand Down