-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
56 lines (49 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
package main
import (
"strings"
"github.com/jmoiron/sqlx"
"github.com/spf13/viper"
)
type configService struct {
db *sqlx.DB
}
type Config struct {
Key string `db:"key" json:"key"`
Value string `db:"value" json:"value,omitempty"`
}
func (s *configService) getConfigs(keys ...string) ([]Config, error) {
config := []Config{}
if len(keys) > 0 {
query, args, _ := sqlx.In("SELECT * FROM config WHERE key IN (?);", keys)
query = s.db.Rebind(query)
err := s.db.Select(&config, query, args...)
return config, err
}
return s.loadConfigs()
}
func (s *configService) loadConfigs() ([]Config, error) {
config := []Config{}
err := s.db.Select(&config, "SELECT * FROM config")
return config, err
}
func (s *configService) updateConfigs(configs []Config) error {
tx, _ := s.db.Begin()
oldConfig := make(map[string]string)
for _, c := range configs {
if c.Key == "SSH_KEY" {
c.Value = strings.ReplaceAll(c.Value, "\\", "/")
}
oldConfig[c.Key] = c.Value
_, err := tx.Exec("UPDATE config SET value = $1 WHERE key = $2", c.Value, c.Key)
if err != nil {
tx.Rollback()
for k, v := range oldConfig {
viper.SetDefault(k, v)
}
return err
}
viper.SetDefault(c.Key, c.Value)
}
tx.Commit()
return nil
}