add options , config

This commit is contained in:
Jay
2018-05-08 16:19:51 +08:00
parent 80e5f0b19c
commit fe884e6931
10 changed files with 172 additions and 12 deletions
+62
View File
@@ -1,4 +1,66 @@
package config
import (
"errors"
"io/ioutil"
"os"
"path"
"gopkg.in/yaml.v2"
"git.trj.tw/golang/go-gallery/modules/utils"
)
// Config struct
type Config struct {
Database struct {
User string `yaml:"user"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Port int `yaml:"port"`
DBName string `yaml:"dbname"`
} `yaml:"database"`
}
var (
conf *Config
)
// LoadConfig from config file
func LoadConfig(p ...string) error {
var fp string
if len(p) > 0 && len(p[0]) > 0 {
fp = p[0]
} else {
wd, err := os.Getwd()
if err != nil {
return err
}
fp = path.Join(wd, "config.yml")
}
fp = utils.ParsePath(fp)
exists := utils.CheckExists(fp, false)
if !exists {
return errors.New("config file not exists")
}
data, err := ioutil.ReadFile(fp)
if err != nil {
return err
}
conf = &Config{}
err = yaml.Unmarshal(data, conf)
if err != nil {
return err
}
return nil
}
// GetConf get config
func GetConf() *Config {
return conf
}
+2 -3
View File
@@ -3,7 +3,6 @@ package middleware
import (
"git.trj.tw/golang/go-gallery/models"
"git.trj.tw/golang/go-gallery/modules/context"
"git.trj.tw/golang/go-gallery/modules/utils"
)
// GetAlbumToNext -
@@ -30,8 +29,8 @@ func GetAlbumToNext(c *context.Context) {
return
}
albumMap := utils.ToMap(album)
c.Set("album", albumMap)
// albumMap := utils.ToMap(album)
c.Set("album", album)
c.Next()
}
+25
View File
@@ -0,0 +1,25 @@
package options
import (
"flag"
)
// Options -
type Options struct {
Config string
}
var (
opts *Options
)
// RegFlag -
func RegFlag() {
opts = &Options{}
flag.StringVar(&opts.Config, "c", "", "config `file path`")
}
// GetOpts -
func GetOpts() *Options {
return opts
}
+52
View File
@@ -1,8 +1,12 @@
package utils
import (
"os"
"path"
"reflect"
"regexp"
"runtime"
"strings"
)
// ToMap struct to map[string]interface{}
@@ -30,3 +34,51 @@ func ToMap(ss interface{}) map[string]interface{} {
return smap
}
// ParsePath - parse file path to absPath
func ParsePath(dst string) string {
wd, err := os.Getwd()
if err != nil {
wd = ""
}
if []rune(dst)[0] == '~' {
home := UserHomeDir()
if len(home) > 0 {
dst = strings.Replace(dst, "~", home, -1)
}
}
if path.IsAbs(dst) {
dst = path.Clean(dst)
return dst
}
str := path.Join(wd, dst)
str = path.Clean(str)
return str
}
// UserHomeDir - get user home directory
func UserHomeDir() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
} else if runtime.GOOS == "plan9" {
env = "home"
}
return os.Getenv(env)
}
// CheckExists - check file exists
func CheckExists(filePath string, allowDir bool) bool {
filePath = ParsePath(filePath)
stat, err := os.Stat(filePath)
if err != nil && !os.IsExist(err) {
return false
}
if !allowDir && stat.IsDir() {
return false
}
return true
}