-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
78 lines (61 loc) · 1.22 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package cmd
import (
"errors"
"io/fs"
"strings"
"github.com/alexfalkowski/go-service/marshaller"
)
var (
// ErrInvalidKind for cmd.
ErrInvalidKind = errors.New("invalid kind")
inputFlag string
)
// ReaderWriter for cmd.
type ReaderWriter interface {
Read() ([]byte, error)
Write(data []byte, mode fs.FileMode) error
Kind() string
}
// Config for cmd.
type Config struct {
m marshaller.Marshaller
rw ReaderWriter
}
// NewConfig for cmd.
func NewConfig(flag string, factory *marshaller.Factory) (*Config, error) {
k, l := splitFlag(flag)
var rw ReaderWriter
switch k {
case "env":
rw = NewENV(l)
case "file":
rw = NewFile(l)
}
if rw == nil {
return nil, ErrInvalidKind
}
m, err := factory.Create(rw.Kind())
if err != nil {
return nil, err
}
return &Config{rw: rw, m: m}, nil
}
// Unmarshal for config.
func (c *Config) Unmarshal(data any) error {
d, err := c.rw.Read()
if err != nil {
return err
}
return c.m.Unmarshal(d, data)
}
// Write for config.
func (c *Config) Write(data []byte, mode fs.FileMode) error {
return c.rw.Write(data, mode)
}
func splitFlag(f string) (string, string) {
c := strings.Split(f, ":")
if len(c) != 2 {
return "env", "CONFIG_FILE"
}
return c[0], c[1]
}