Initial dumb servers
This commit is contained in:
34
server/config/config.go
Normal file
34
server/config/config.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"local/storage"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var config Config
|
||||
var lock = &sync.RWMutex{}
|
||||
|
||||
type Config struct {
|
||||
db string
|
||||
DB storage.DB
|
||||
Port string
|
||||
Addr string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
func Values() Config {
|
||||
lock.RLock()
|
||||
defer lock.RUnlock()
|
||||
return config
|
||||
}
|
||||
|
||||
func (c Config) String() string {
|
||||
return fmt.Sprintf(
|
||||
"port:%v db:%v addr:%v user:*** pass:***",
|
||||
c.Port,
|
||||
c.db,
|
||||
c.Addr,
|
||||
)
|
||||
}
|
||||
28
server/config/new.go
Normal file
28
server/config/new.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"local/storage"
|
||||
"os"
|
||||
)
|
||||
|
||||
func New() error {
|
||||
config = Config{
|
||||
db: orEnv(storage.MAP.String(), "DB", "DATABASE"),
|
||||
Addr: orEnv("", "ADDR", "FILE"),
|
||||
Username: orEnv("", "USER", "USERNAME"),
|
||||
Password: orEnv("", "PASS", "PASSWORD"),
|
||||
Port: orEnv("21412", "PORT", "LISTEN"),
|
||||
}
|
||||
DB, err := storage.New(storage.TypeFromString(config.db), config.Addr, config.Username, config.Password)
|
||||
config.DB = DB
|
||||
return err
|
||||
}
|
||||
|
||||
func orEnv(def, key string, keys ...string) string {
|
||||
for _, key := range append(keys, key) {
|
||||
if v, ok := os.LookupEnv(key); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
37
server/config/new_test.go
Normal file
37
server/config/new_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
invalidEnv := "&&&&&&"
|
||||
keys := []string{
|
||||
"DB",
|
||||
"DATABASE",
|
||||
"ADDR",
|
||||
"PATH",
|
||||
"USER",
|
||||
"USERNAME",
|
||||
"PASS",
|
||||
"PASSWORD",
|
||||
}
|
||||
was := make(map[string]string)
|
||||
for _, k := range keys {
|
||||
v, ok := os.LookupEnv(k)
|
||||
if !ok {
|
||||
v = invalidEnv
|
||||
}
|
||||
was[k] = v
|
||||
}
|
||||
defer func() {
|
||||
for k, v := range was {
|
||||
if v != invalidEnv {
|
||||
os.Setenv(k, v)
|
||||
} else {
|
||||
os.Unsetenv(k)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
Reference in New Issue
Block a user