ipld-eth-server/pkg/config/config.go

80 lines
1.6 KiB
Go
Raw Normal View History

package config
2017-11-02 22:37:27 +00:00
import (
"os"
"fmt"
"path/filepath"
"path"
"runtime"
"errors"
"net/url"
2017-11-02 22:37:27 +00:00
"github.com/BurntSushi/toml"
)
type Config struct {
Database Database
2017-11-02 22:37:27 +00:00
Client Client
}
var NewErrConfigFileNotFound = func(environment string) error {
return errors.New(fmt.Sprintf("No configuration found for environment: %v", environment))
}
var NewErrBadConnectionString = func(connectionString string) error {
return errors.New(fmt.Sprintf("connection string is invalid: %v", connectionString))
}
func NewConfig(environment string) (Config, error) {
2017-11-02 22:37:27 +00:00
filenameWithExtension := fmt.Sprintf("%s.toml", environment)
2017-11-14 15:10:48 +00:00
absolutePath := filepath.Join(ProjectRoot(), "environments", filenameWithExtension)
config, err := parseConfigFile(absolutePath)
if err != nil {
return Config{}, NewErrConfigFileNotFound(environment)
} else {
if !filepath.IsAbs(config.Client.IPCPath) && !isUrl(config.Client.IPCPath) {
config.Client.IPCPath = filepath.Join(ProjectRoot(), config.Client.IPCPath)
}
return config, nil
}
2017-11-02 22:37:27 +00:00
}
func ProjectRoot() string {
var _, filename, _, _ = runtime.Caller(0)
2017-11-06 18:53:43 +00:00
return path.Join(path.Dir(filename), "..", "..")
2017-11-02 22:37:27 +00:00
}
func isUrl(s string) bool {
_, err := url.ParseRequestURI(s)
if err == nil {
return true
}
return false
}
func fileExists(s string) bool {
_, err := os.Stat(s)
if err == nil {
return true
}
return false
}
func parseConfigFile(filePath string) (Config, error) {
2017-11-02 22:37:27 +00:00
var cfg Config
if !isUrl(filePath) && !fileExists(filePath) {
return Config{}, NewErrBadConnectionString(filePath)
} else {
_, err := toml.DecodeFile(filePath, &cfg)
if err != nil {
return Config{}, err
}
return cfg, nil
2017-11-02 22:37:27 +00:00
}
}