63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package serve
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"local/dynamodb/server/config"
|
|
"local/s2sa/s2sa/server/router"
|
|
"local/storage"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func (s *Server) Routes() error {
|
|
if err := s.router.Add("/"+router.Wildcard, s.CatchAll); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) CatchAll(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) {
|
|
config := config.Values()
|
|
key := strings.Split(r.URL.Path, "/")[1]
|
|
if v, err := config.DB.Get(key); err == storage.ErrNotFound {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
} else if err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
} else {
|
|
w.Write(v)
|
|
}
|
|
}
|
|
|
|
func (s *Server) put(w http.ResponseWriter, r *http.Request) {
|
|
config := config.Values()
|
|
key := strings.Split(r.URL.Path, "/")[1]
|
|
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 := config.DB.Set(key, value); err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|