You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cronsun/web/node.go

101 lines
2.2 KiB

8 years ago
package web
import (
"encoding/json"
"net/http"
"strings"
8 years ago
v3 "github.com/coreos/etcd/clientv3"
"github.com/gorilla/mux"
"sunteng/commons/log"
"sunteng/cronsun/conf"
"sunteng/cronsun/models"
)
type Node struct{}
var ngKeyDeepLen = len(conf.Config.Group)
8 years ago
func (n *Node) UpdateGroup(w http.ResponseWriter, r *http.Request) {
g := models.Group{}
de := json.NewDecoder(r.Body)
var err error
if err = de.Decode(&g); err != nil {
outJSONError(w, http.StatusBadRequest, err.Error())
return
}
8 years ago
defer r.Body.Close()
8 years ago
var successCode = http.StatusOK
g.ID = strings.TrimSpace(g.ID)
if len(g.ID) == 0 {
successCode = http.StatusCreated
g.ID = models.NextID()
} else {
}
if err = g.Check(); err != nil {
outJSONError(w, http.StatusBadRequest, err.Error())
return
}
8 years ago
// @TODO rev
var rev int64 = 0
if _, err = g.Put(rev); err != nil {
outJSONError(w, http.StatusBadRequest, err.Error())
return
}
8 years ago
outJSONWithCode(w, successCode, nil)
}
8 years ago
func (n *Node) GetGroups(w http.ResponseWriter, r *http.Request) {
resp, err := models.DefalutClient.Get(conf.Config.Group, v3.WithPrefix(), v3.WithSort(v3.SortByKey, v3.SortAscend))
if err != nil {
outJSONError(w, http.StatusInternalServerError, err.Error())
return
}
8 years ago
var list = make([]*models.Group, 0, resp.Count)
for i := range resp.Kvs {
8 years ago
g := models.Group{}
err = json.Unmarshal(resp.Kvs[i].Value, &g)
if err != nil {
8 years ago
log.Errorf("node.GetGroups(key: %s) error: %s", string(resp.Kvs[i].Key), err.Error())
outJSONError(w, http.StatusInternalServerError, err.Error())
return
}
8 years ago
list = append(list, &g)
}
8 years ago
outJSON(w, list)
}
8 years ago
func (n *Node) GetGroupByGroupId(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
g, err := models.GetGroupById(vars["id"])
if err != nil {
outJSONError(w, http.StatusInternalServerError, err.Error())
return
}
8 years ago
if g == nil {
outJSONWithCode(w, http.StatusNotFound, nil)
return
}
8 years ago
outJSON(w, g)
}
8 years ago
func (n *Node) DeleteGroup(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
_, err := models.DeleteGroupById(vars["id"])
if err != nil {
outJSONError(w, http.StatusInternalServerError, err.Error())
return
}
outJSONWithCode(w, http.StatusNoContent, nil)
8 years ago
}