55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package routes
|
|
|
|
import (
|
|
"encoding/json"
|
|
"gitea.deepak.science/deepak/gogmagog/models"
|
|
"github.com/go-chi/chi"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
func newPlanRouter(m *models.Model) http.Handler {
|
|
router := chi.NewRouter()
|
|
router.Get("/", getAllPlansFunc(m))
|
|
router.Get("/{planid}", getPlanByIDFunc(m))
|
|
return router
|
|
}
|
|
|
|
func getAllPlansFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
plans, err := m.Plans()
|
|
if err != nil {
|
|
serverError(w, err)
|
|
return
|
|
}
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(plans); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getPlanByIDFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(chi.URLParam(r, "planid"))
|
|
if err != nil {
|
|
notFoundHandler(w, r)
|
|
return
|
|
}
|
|
plan, err := m.Plan(id)
|
|
if err != nil {
|
|
if models.IsNotFoundError(err) {
|
|
notFoundHandler(w, r)
|
|
return
|
|
}
|
|
serverError(w, err)
|
|
return
|
|
|
|
}
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(plan); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|