Initial commit

This commit is contained in:
2020-12-21 15:56:56 +01:00
commit d9a6c14041
50 changed files with 10235 additions and 0 deletions

81
internal/config/config.go Normal file
View File

@ -0,0 +1,81 @@
package config
import (
"io"
"io/ioutil"
"github.com/caarlos0/env/v6"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type Config struct {
HTTP HTTPConfig `yaml:"http"`
Data DataConfig `yaml:"data"`
}
type HTTPConfig struct {
Address string `yaml:"address" env:"FAKESMS_HTTP_ADDRESS"`
TemplateDir string `yaml:"templateDir" env:"FAKESMS_HTTP_TEMPLATEDIR"`
PublicDir string `yaml:"publicDir" env:"FAKESMS_HTTP_PUBLICDIR"`
}
type DataConfig struct {
Path string `yaml:"path" env:"FAKESMS_DATA_PATH"`
}
// NewFromFile retrieves the configuration from the given file
func NewFromFile(filepath string) (*Config, error) {
config := NewDefault()
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.Wrapf(err, "could not read file '%s'", filepath)
}
if err := yaml.Unmarshal(data, config); err != nil {
return nil, errors.Wrapf(err, "could not unmarshal configuration")
}
return config, nil
}
func WithEnvironment(conf *Config) error {
if err := env.Parse(conf); err != nil {
return err
}
return nil
}
func NewDumpDefault() *Config {
config := NewDefault()
return config
}
func NewDefault() *Config {
return &Config{
HTTP: HTTPConfig{
Address: ":8080",
TemplateDir: "template",
PublicDir: "public",
},
Data: DataConfig{
Path: "fakesms.db",
},
}
}
func Dump(config *Config, w io.Writer) error {
data, err := yaml.Marshal(config)
if err != nil {
return errors.Wrap(err, "could not dump config")
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,9 @@
package config
import "gitlab.com/wpetit/goweb/service"
func ServiceProvider(config *Config) service.Provider {
return func(ctn *service.Container) (interface{}, error) {
return config, nil
}
}

View File

@ -0,0 +1,33 @@
package config
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "config"
// From retrieves the config service in the given container
func From(container *service.Container) (*Config, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Config)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the config service in the given container or panic otherwise
func Must(container *service.Container) *Config {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}