zoorest/rest/api.go

111 lines
1.9 KiB
Go
Raw Normal View History

2017-02-15 17:09:28 +03:00
package rest
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"time"
)
// Ls ...
type Ls struct {
Childrens []string `json:"childrens"`
Path string `json:"path"`
State string `json:"state"`
2017-02-15 17:24:58 +03:00
Error string `json:"error"`
2017-02-15 17:09:28 +03:00
}
// Get ...
type Get struct {
Path string `json:"path"`
State string `json:"state"`
2017-02-15 17:24:58 +03:00
Error string `json:"error"`
2017-02-15 17:09:28 +03:00
Data []byte `json:"data"`
}
// LS ...
func (zk ZooNode) LS(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
path := vars["path"]
ch := make(chan Ls)
go func() { ch <- zk.GetChildrens(path) }()
childrens := <-ch
data, err := json.Marshal(childrens)
if err != nil {
w.WriteHeader(500)
2017-02-15 17:24:58 +03:00
w.Write([]byte("JSON parsing failure"))
return
}
if childrens.Error != "" {
w.WriteHeader(500)
w.Write(data)
return
2017-02-15 17:09:28 +03:00
}
2017-02-15 17:24:58 +03:00
2017-02-15 17:09:28 +03:00
w.WriteHeader(200)
w.Write(data)
}
2017-02-15 19:13:12 +03:00
// RM ...
func (zk ZooNode) RM(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
path := vars["path"]
go func() { zk.RMR(path) }()
w.WriteHeader(200)
// w.Write(data)
}
2017-02-15 17:09:28 +03:00
// GET ...
func (zk ZooNode) GET(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
path := vars["path"]
ch := make(chan Get)
go func() { ch <- zk.GetNode(path) }()
childrens := <-ch
data, err := json.Marshal(childrens)
if err != nil {
w.WriteHeader(500)
2017-02-15 17:24:58 +03:00
w.Write([]byte("JSON parsing failure"))
return
2017-02-15 17:09:28 +03:00
}
2017-02-15 17:24:58 +03:00
if childrens.Error != "" {
w.WriteHeader(500)
w.Write(data)
return
}
2017-02-15 17:09:28 +03:00
w.WriteHeader(200)
w.Write(data)
}
// Serve ...
func Serve(listen string, zk ZooNode) {
r := mux.NewRouter()
r.HandleFunc("/v1/ls{path:[a-z0-9-_/.:]+}", zk.LS)
r.HandleFunc("/v1/get{path:[a-z0-9-_/.:]+}", zk.GET)
2017-02-15 19:13:12 +03:00
r.HandleFunc("/v1/rmr{path:[a-z0-9-_/.:]+}", zk.RM)
2017-02-15 17:09:28 +03:00
http.Handle("/", r)
srv := http.Server{
Handler: r,
Addr: listen,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Print("Listening API on ", listen)
log.Fatal(srv.ListenAndServe())
}