72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (c *Config) setup(r *mux.Router) {
|
|
r.HandleFunc("/{key}", c.deleteValue).Methods(http.MethodDelete)
|
|
r.HandleFunc("/{key}", c.getValue).Methods(http.MethodGet)
|
|
r.HandleFunc("/", c.getConfigValues).Methods(http.MethodGet)
|
|
r.HandleFunc("/", c.postConfigValue).Methods(http.MethodPost)
|
|
}
|
|
|
|
func (c *Config) getConfigValues(w http.ResponseWriter, r *http.Request) {
|
|
log.Debug().Msg("getConfigValues")
|
|
vals, err := c.getAll()
|
|
if err != nil {
|
|
http.Error(w, mkJSONError(err.Error()), http.StatusInternalServerError)
|
|
}
|
|
json.NewEncoder(w).Encode(vals)
|
|
}
|
|
|
|
func (c *Config) postConfigValue(w http.ResponseWriter, r *http.Request) {
|
|
log.Debug().Msg("postConfigValues")
|
|
configPost := configValue{}
|
|
err := json.NewDecoder(r.Body).Decode(&configPost)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
}
|
|
c.set(configPost.Key, configPost)
|
|
resp := struct {
|
|
Status string `json:"status"`
|
|
}{"success"}
|
|
log.Debug().Msgf("post success, returning struct %v", resp)
|
|
err = json.NewEncoder(w).Encode(resp)
|
|
if err != nil {
|
|
http.Error(w, mkJSONError(err.Error()), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func (c *Config) deleteValue(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
log.Debug().Msgf("deleteValue %s", vars["key"])
|
|
err := c.delete(vars["key"])
|
|
if err != nil {
|
|
http.Error(w, mkJSONError(err.Error()), http.StatusInternalServerError)
|
|
}
|
|
http.Error(w, "", http.StatusNoContent)
|
|
}
|
|
|
|
func (c *Config) getValue(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
log.Debug().Msgf("getValue %s", vars["key"])
|
|
v, err := c.get(vars["key"])
|
|
if err != nil {
|
|
http.Error(w, mkJSONError(err.Error()), http.StatusNotFound)
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func mkJSONError(msg string) string {
|
|
j, _ := json.Marshal(struct {
|
|
Error string `json:"error"`
|
|
}{msg})
|
|
return string(j)
|
|
}
|