-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
54 lines (47 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
package main
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis_rate/v9"
"io/ioutil"
"os"
)
type Config struct {
ListenPort int `json:"listen_port"`
RedisAddress string `json:"redis_address"`
Namespaces map[string]Namespace `json:"namespaces"`
}
type Namespace struct {
Rate int `json:"rate"`
Period string `json:"period"`
}
func (n Namespace) getLimit() redis_rate.Limit {
switch n.Period {
case "SECOND":
return redis_rate.PerSecond(n.Rate)
case "MINITE":
return redis_rate.PerMinute(n.Rate)
case "HOUR":
return redis_rate.PerHour(n.Rate)
default:
panic(fmt.Sprintf("Invalid value for Period: %s", n.Period))
}
}
func LoadConfig() (Config, error) {
filePath := os.Getenv("CONFIG_FILE")
if len(filePath) == 0 {
filePath = "/etc/rate_limiter_svc/conf.json"
}
configFile, err := os.Open(filePath)
if err != nil {
return Config{}, fmt.Errorf("error opening config file %s: %w", filePath, err)
}
defer configFile.Close()
configBytes, _ := ioutil.ReadAll(configFile)
var config Config
if err := json.Unmarshal(configBytes, &config); err != nil {
return Config{}, fmt.Errorf("error unmarshalling config json: %w", err)
}
// TODO: validate
return config, nil
}