/
config_api.go
61 lines (50 loc) · 1.35 KB
/
config_api.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
package main
import (
"io/ioutil"
"net/http"
"github.com/julienschmidt/httprouter"
)
const (
configURI = "/config"
)
func (a *ChangeAgent) initConfigAPI(prefix string) {
a.router.GET(prefix+configURI, a.handleGetRaftConfig)
a.router.POST(prefix+configURI, a.handleSetRaftConfig)
a.router.PUT(prefix+configURI, a.handleSetRaftConfig)
}
func (a *ChangeAgent) handleGetRaftConfig(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
cfg := a.raft.GetRaftConfig()
cfgBytes, err := cfg.Store()
if err != nil {
writeError(resp, http.StatusInternalServerError, err)
return
}
resp.Header().Set("Content-Type", yamlContent)
resp.Write(cfgBytes)
}
func (a *ChangeAgent) handleSetRaftConfig(
resp http.ResponseWriter, req *http.Request, params httprouter.Params) {
contentType := req.Header.Get("Content-Type")
if !yamlContentRe.MatchString(contentType) {
resp.WriteHeader(http.StatusUnsupportedMediaType)
return
}
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
writeError(resp, http.StatusBadRequest, err)
return
}
ix, err := a.raft.UpdateConfiguration(body)
if err != nil {
writeError(resp, http.StatusBadRequest, err)
return
}
err = a.raft.WaitForCommit(ix)
if err != nil {
writeError(resp, http.StatusInternalServerError, err)
return
}
a.handleGetRaftConfig(resp, req, params)
}