Initial dumb servers

This commit is contained in:
Bel LaPointe
2019-03-14 14:43:02 -06:00
commit 1f679f4c06
10 changed files with 381 additions and 0 deletions

62
server/serve/routes.go Normal file
View File

@@ -0,0 +1,62 @@
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
}
}