ok resty enough

This commit is contained in:
Bel LaPointe
2024-02-20 08:45:29 -07:00
parent b737b440b1
commit 706522eeef
3 changed files with 23 additions and 15 deletions

View File

@@ -13,6 +13,7 @@ import (
"os"
"os/signal"
"path"
"regexp"
"strings"
"syscall"
@@ -160,14 +161,16 @@ func (h Handler) handle(session Session, w http.ResponseWriter, r *http.Request)
http.FileServer(public).ServeHTTP(w, r)
return nil
}
if strings.HasPrefix(r.URL.Path, "/api/v1/questions/") {
return h.handleAPIV1Question(session, w, r)
handlers := map[string]func(Session, http.ResponseWriter, *http.Request) error{
`^/api/v1/questions$`: h.handleAPIV1Questions,
`^/api/v1/questions/[^/]*$`: h.handleAPIV1Question,
`^/api/v1/questions/[^/]*/answers$`: h.handleAPIV1QuestionsAnswers,
}
if strings.HasPrefix(r.URL.Path, "/api/v1/questions") {
return h.handleAPIV1Questions(session, w, r)
}
if strings.HasPrefix(r.URL.Path, "/api/v1/answers") {
return h.handleAPIV1Answers(session, w, r)
for k, v := range handlers {
if regexp.MustCompile(k).MatchString(r.URL.Path) {
return v(session, w, r)
}
}
http.NotFound(w, r)
return nil
@@ -190,19 +193,19 @@ func (h Handler) handleAPIV1Questions(session Session, w http.ResponseWriter, r
return json.NewEncoder(w).Encode(qs)
}
func (h Handler) handleAPIV1Answers(session Session, w http.ResponseWriter, r *http.Request) error {
func (h Handler) handleAPIV1QuestionsAnswers(session Session, w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case http.MethodGet:
return h.handleAPIV1AnswersGet(session, w, r)
return h.handleAPIV1QuestionsAnswersGet(session, w, r)
case http.MethodPost:
return h.handleAPIV1AnswersPost(session, w, r)
return h.handleAPIV1QuestionsAnswersPost(session, w, r)
}
http.NotFound(w, r)
return nil
}
func (h Handler) handleAPIV1AnswersGet(session Session, w http.ResponseWriter, r *http.Request) error {
qid := path.Base(r.URL.Path)
func (h Handler) handleAPIV1QuestionsAnswersGet(session Session, w http.ResponseWriter, r *http.Request) error {
qid := path.Base(path.Dir(r.URL.Path))
as, err := h.db.GetAnswers(qid)
if err != nil {
return err
@@ -210,8 +213,8 @@ func (h Handler) handleAPIV1AnswersGet(session Session, w http.ResponseWriter, r
return json.NewEncoder(w).Encode(as)
}
func (h Handler) handleAPIV1AnswersPost(session Session, w http.ResponseWriter, r *http.Request) error {
qid := path.Base(r.URL.Path)
func (h Handler) handleAPIV1QuestionsAnswersPost(session Session, w http.ResponseWriter, r *http.Request) error {
qid := path.Base(path.Dir(r.URL.Path))
uid := session.User.ID
var a Answer
if err := json.NewDecoder(r.Body).Decode(&a); err != nil {