This repository has been archived by the owner on Mar 7, 2023. It is now read-only.
/
config-handler.go
83 lines (67 loc) · 2.33 KB
/
config-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
package server
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/hashicorp/go-hclog"
"github.com/leonardochaia/vendopunkto/errors"
"github.com/leonardochaia/vendopunkto/internal/conf"
)
// ConfigHandler for configurations
type ConfigHandler struct {
logger hclog.Logger
runtime *conf.Runtime
manager conf.Manager
}
// InternalRoutes creates a router for the internal API
func (handler *ConfigHandler) InternalRoutes() chi.Router {
router := chi.NewRouter()
router.Get("/", errors.WrapHandler(handler.getConfiguration))
router.Post("/", errors.WrapHandler(handler.updateConfiguration))
return router
}
func (handler *ConfigHandler) getConfiguration(w http.ResponseWriter, r *http.Request) error {
const op errors.Op = "api.configHandler.getConfiguration"
render.JSON(w, r, handler.runtime.AllSettings())
return nil
}
func (handler *ConfigHandler) updateConfiguration(w http.ResponseWriter, r *http.Request) error {
const op errors.Op = "api.configHandler.updateConfiguration"
// we don't know the type of value. it could be a string or a []string
var params = make(map[string]json.RawMessage)
if err := render.DecodeJSON(r.Body, ¶ms); err != nil {
return errors.E(op, errors.Parameters, err)
}
for key, rawMessage := range params {
if !handler.runtime.IsKnownKey(key) {
err := errors.Errorf("Provided key is not a known runtime config key: %s", key)
return errors.E(op, errors.Parameters, err)
}
var arrValue []string
// try to unmarshal into a []string first
if err := json.Unmarshal(rawMessage, &arrValue); err != nil {
// if it's not an array, try with string.
var strValue string
if err := json.Unmarshal(rawMessage, &strValue); err != nil {
err = errors.Errorf("Attempted to parse JSON as string or []string and failed. Key: %s, error: %s",
key, err)
return errors.E(op, errors.Parameters, err)
}
// save the string value
err = handler.manager.SaveConfiguration(key, strValue)
if err != nil {
return errors.E(op, errors.Parameters, err)
}
continue
}
// save the array value
err := handler.manager.SaveConfiguration(key, arrValue)
if err != nil {
return errors.E(op, errors.Parameters, err)
}
// TODO: validate that the provided values make sense.
}
render.JSON(w, r, handler.runtime.AllSettings())
return nil
}