83 lines
1.7 KiB
Go
83 lines
1.7 KiB
Go
package serve
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"local/dynamodb/server/config"
|
|
"local/router"
|
|
"local/storage"
|
|
"log"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
func (s *Server) Routes() error {
|
|
if err := s.router.Add("/"+router.Wildcard, s.SimpleCatchAll); err != nil {
|
|
return err
|
|
}
|
|
if err := s.router.Add("/"+router.Wildcard+"/"+router.Wildcard, s.NSCatchAll); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) SimpleCatchAll(w http.ResponseWriter, r *http.Request) {
|
|
r.URL.Path = path.Join("/"+storage.DefaultNamespace, r.URL.Path)
|
|
s.NSCatchAll(w, r)
|
|
}
|
|
|
|
func (s *Server) NSCatchAll(w http.ResponseWriter, r *http.Request) {
|
|
foo := http.NotFound
|
|
switch strings.ToLower(r.Method) {
|
|
case "get":
|
|
foo = s.get
|
|
case "put":
|
|
foo = s.put
|
|
case "delete":
|
|
foo = s.put
|
|
}
|
|
foo(w, r)
|
|
}
|
|
|
|
func (s *Server) get(w http.ResponseWriter, r *http.Request) {
|
|
db := config.Values().DB
|
|
ns := strings.Split(r.URL.Path, "/")[1]
|
|
var key string
|
|
if len(strings.Split(r.URL.Path, "/")) < 3 {
|
|
key = ns
|
|
ns = ""
|
|
} else {
|
|
key = strings.Split(r.URL.Path, "/")[2]
|
|
}
|
|
if value, err := db.Get(key, ns); err == storage.ErrNotFound {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
} else if err != nil {
|
|
log.Println(err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
} else {
|
|
w.Write(value)
|
|
}
|
|
}
|
|
|
|
func (s *Server) put(w http.ResponseWriter, r *http.Request) {
|
|
db := config.Values().DB
|
|
ns := strings.Split(r.URL.Path, "/")[1]
|
|
key := strings.Split(r.URL.Path, "/")[2]
|
|
if r == nil || r.Body == nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
value, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := db.Set(key, value, ns); err != nil {
|
|
log.Println(err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|