Use Viper for Configuration

This commit is contained in:
Henrique Dias 2017-07-29 13:28:18 +01:00
parent adfc66896d
commit aa6631c408
No known key found for this signature in database
GPG Key ID: 936F5EB68D786730

View File

@ -1,68 +1,93 @@
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strconv"
"path/filepath"
"strings"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
"github.com/hacdias/filemanager"
"github.com/hacdias/fileutils"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
)
// confFile contains the configuration file for this File Manager instance.
// If the user chooses to use a configuration file, the flags will be ignored.
type confFile struct {
Database string `json:"database"`
Scope string `json:"scope"`
Address string `json:"address"`
Commands []string `json:"commands"`
Port int `json:"port"`
Logger string `json:"log"`
AllowCommands bool `json:"allowCommands"`
AllowEdit bool `json:"allowEdit"`
AllowNew bool `json:"allowNew"`
}
var (
addr string
config string
database string
scope string
commands string
port string
logfile string
port int
allowCommands bool
allowEdit bool
allowNew bool
)
func init() {
flag.StringVar(&config, "config", "", "JSON configuration file")
flag.StringVar(&port, "port", "0", "HTTP Port (default is random)")
flag.StringVar(&addr, "address", "", "Address to listen to (default is all of them)")
flag.StringVar(&database, "database", "./filemanager.db", "Database path")
flag.StringVar(&scope, "scope", ".", "Default scope for new users")
flag.StringVar(&commands, "commands", "git svn hg", "Space separated commands available for new users")
flag.StringVar(&logfile, "log", "stdout", "Logger to log the errors.")
flag.BoolVar(&allowCommands, "allow-commands", true, "Default allow commands option")
flag.BoolVar(&allowEdit, "allow-edit", true, "Default allow edit option")
flag.BoolVar(&allowNew, "allow-new", true, "Default allow new option")
flag.StringVarP(&config, "config", "c", "", "JSON configuration file")
flag.IntVarP(&port, "port", "p", 0, "HTTP Port (default is random)")
flag.StringVarP(&addr, "address", "a", "", "Address to listen to (default is all of them)")
flag.StringVarP(&database, "database", "d", "./filemanager.db", "Database file")
flag.StringVarP(&logfile, "log", "l", "stdout", "Errors logger; can use 'stdout', 'stderr' or file")
flag.StringVarP(&scope, "scope", "s", ".", "Default scope option for new users")
flag.StringVar(&commands, "commands", "git svn hg", "Default commands option for new users")
flag.BoolVar(&allowCommands, "allow-commands", true, "Default allow commands option for new users")
flag.BoolVar(&allowEdit, "allow-edit", true, "Default allow edit option for new users")
flag.BoolVar(&allowNew, "allow-new", true, "Default allow new option for new users")
}
func setupViper() {
viper.SetDefault("Address", "")
viper.SetDefault("Port", "0")
viper.SetDefault("Database", "./filemanager.db")
viper.SetDefault("Scope", ".")
viper.SetDefault("Logger", "stdout")
viper.SetDefault("Commands", []string{"git", "svn", "hg"})
viper.SetDefault("AllowCommmands", true)
viper.SetDefault("AllowEdit", true)
viper.SetDefault("AllowNew", true)
viper.BindPFlag("Port", flag.Lookup("port"))
viper.BindPFlag("Address", flag.Lookup("address"))
viper.BindPFlag("Database", flag.Lookup("database"))
viper.BindPFlag("Scope", flag.Lookup("scope"))
viper.BindPFlag("Logger", flag.Lookup("log"))
viper.BindPFlag("Commands", flag.Lookup("commands"))
viper.BindPFlag("AllowCommands", flag.Lookup("allow-commands"))
viper.BindPFlag("AllowEdit", flag.Lookup("allow-edit"))
viper.BindPFlag("AlowNew", flag.Lookup("allow-new"))
viper.SetConfigName("filemanager")
viper.AddConfigPath(".")
}
func main() {
setupViper()
flag.Parse()
// Set up process log before anything bad happens
switch logfile {
// Add a configuration file if set.
if config != "" {
viper.SetConfigName(strings.TrimSuffix(config, filepath.Ext(config)))
}
// Read configuration from a file if exists.
err := viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigParseError); ok {
panic(err)
}
}
// Set up process log before anything bad happens.
switch viper.GetString("Logger") {
case "stdout":
log.SetOutput(os.Stdout)
case "stderr":
@ -78,57 +103,33 @@ func main() {
})
}
if config != "" {
loadConfig()
}
fm, err := filemanager.New(database, filemanager.User{
AllowCommands: allowCommands,
AllowEdit: allowEdit,
AllowNew: allowNew,
Commands: strings.Split(strings.TrimSpace(commands), " "),
// Create a File Manager instance.
fm, err := filemanager.New(viper.GetString("Database"), filemanager.User{
AllowCommands: viper.GetBool("AllowCommands"),
AllowEdit: viper.GetBool("AllowEdit"),
AllowNew: viper.GetBool("AllowNew"),
Commands: viper.GetStringSlice("Commands"),
Rules: []*filemanager.Rule{},
CSS: "",
FileSystem: fileutils.Dir(scope),
FileSystem: fileutils.Dir(viper.GetString("Scope")),
})
if err != nil {
log.Fatal(err)
}
fm.SetBaseURL("/")
fm.SetPrefixURL("/")
listener, err := net.Listen("tcp", addr+":"+port)
// Builds the address and a listener.
laddr := viper.GetString("Address") + ":" + viper.GetString("Port")
listener, err := net.Listen("tcp", laddr)
if err != nil {
log.Fatal(err)
}
// Tell the user the port in which is listening.
fmt.Println("Listening on", listener.Addr().String())
// Starts the server.
if err := http.Serve(listener, fm); err != nil {
log.Fatal(err)
}
}
func loadConfig() {
file, err := ioutil.ReadFile(config)
if err != nil {
log.Fatal(err)
}
var conf *confFile
err = json.Unmarshal(file, &conf)
if err != nil {
log.Fatal(err)
}
database = conf.Database
scope = conf.Scope
addr = conf.Address
logfile = conf.Logger
commands = strings.Join(conf.Commands, " ")
port = strconv.Itoa(conf.Port)
allowNew = conf.AllowNew
allowEdit = conf.AllowEdit
allowCommands = conf.AllowCommands
}