From 6f7aa5060417cc79769f2d15d5e77b17329759bc Mon Sep 17 00:00:00 2001 From: Denis Zheleztsov Date: Fri, 17 Feb 2017 11:05:54 +0300 Subject: [PATCH] api method up --- rest/api.go | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/rest/api.go b/rest/api.go index f2c679d..b5316fa 100644 --- a/rest/api.go +++ b/rest/api.go @@ -3,8 +3,10 @@ package rest import ( "encoding/json" "github.com/gorilla/mux" + "io/ioutil" "log" "net/http" + "strings" "time" ) @@ -50,15 +52,63 @@ func (zk ZooNode) LS(w http.ResponseWriter, r *http.Request) { w.Write(data) } +// ReadRequestBody ... +func ReadRequestBody(req *http.Request) ([]byte, error) { + body, err := ioutil.ReadAll(req.Body) + if err != nil { + return []byte(""), err + } + + return body, err +} + +// UP ... +func (zk ZooNode) UP(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + path := vars["path"] + + ch := make(chan string) + // Read request body as []byte + content, err := ReadRequestBody(r) + if err != nil { + w.WriteHeader(500) + w.Write([]byte(err.Error())) + return + } + + // Create node + if r.Method == "PUT" { + go func() { ch <- zk.CreateNode(path, content) }() + } else if r.Method == "POST" { + go func() { ch <- zk.UpdateNode(path, content) }() + } else { + e := strings.Join([]string{r.Method, "not alowed"}, " ") + w.WriteHeader(500) + w.Write([]byte(e)) + return + } + defer r.Body.Close() + + state := <-ch + + w.WriteHeader(200) + w.Write([]byte(state)) +} + // RM ... func (zk ZooNode) RM(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + e := strings.Join([]string{r.Method, "not alowed"}, " ") + w.WriteHeader(500) + w.Write([]byte(e)) + return + } vars := mux.Vars(r) path := vars["path"] go func() { zk.RMR(path) }() w.WriteHeader(200) - // w.Write(data) } // GET ... @@ -95,6 +145,7 @@ func Serve(listen string, zk ZooNode) { r.HandleFunc("/v1/ls{path:[a-z0-9-_/.:]+}", zk.LS) r.HandleFunc("/v1/get{path:[a-z0-9-_/.:]+}", zk.GET) r.HandleFunc("/v1/rmr{path:[a-z0-9-_/.:]+}", zk.RM) + r.HandleFunc("/v1/up{path:[a-z0-9-_/.:]+}", zk.UP) http.Handle("/", r)