-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
112 lines (89 loc) · 2.12 KB
/
handler.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package main
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"strings"
"github.com/nats-io/go-nats"
"github.com/r3labs/akira"
)
// Handler describes a NATS handler and its dependencies.
type Handler struct {
Nats akira.Connector
ConfigPath string
}
// ConfigGet handles requests to config.get.*
func (h *Handler) ConfigGet(msg *nats.Msg) {
service := extractService(msg.Subject)
data := getServiceConfig(service, h.ConfigPath)
err := h.Nats.Publish(msg.Reply, data)
if err != nil {
log.Println(err)
}
}
// ConfigSet handles requests to config.set.*
func (h *Handler) ConfigSet(msg *nats.Msg) {
service := extractService(msg.Subject)
data := setServiceConfig(service, h.ConfigPath, msg.Data)
err := h.Nats.Publish(msg.Reply, data)
if err != nil {
log.Println(err)
}
}
func extractService(subject string) string {
s := strings.Split(subject, ".")
return s[len(s)-1]
}
func getServiceConfig(service, configPath string) []byte {
c := make(map[string]interface{})
file, err := os.Open(configPath)
if err != nil {
log.Println(err)
}
data, err := ioutil.ReadAll(file)
if err != nil {
log.Println(err)
}
err = json.Unmarshal(data, &c)
if err != nil {
log.Println(err)
}
data, err = json.Marshal(c[service])
if err != nil {
log.Println(err)
}
return data
}
func setServiceConfig(service, configPath string, msg []byte) []byte {
c := make(map[string]interface{})
file, err := os.Open(configPath)
if err != nil {
log.Println(err)
}
data, err := ioutil.ReadAll(file)
if err != nil {
log.Println(err)
}
err = json.Unmarshal(data, &c)
if err != nil {
log.Println(err)
}
msg = []byte(`{"` + service + `": ` + string(msg) + `}`)
err = json.Unmarshal(msg, &c)
if err != nil {
log.Println(err)
}
data, err = json.MarshalIndent(c, "", " ")
if err != nil {
log.Println(err)
}
err = ioutil.WriteFile(configPath, data, 0644)
if err != nil {
log.Println(err)
}
return data
}