All checks were successful
gitea-deepak/gogmagog/pipeline/head This commit looks good
71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package routes
|
|
|
|
import (
|
|
"encoding/json"
|
|
"gitea.deepak.science/deepak/gogmagog/models"
|
|
"github.com/go-chi/chi"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
func newActionRouter(m *models.Model) http.Handler {
|
|
router := chi.NewRouter()
|
|
router.Get("/", getActionsFunc(m))
|
|
router.Get("/{actionid}", getActionByIDFunc(m))
|
|
return router
|
|
}
|
|
|
|
func getActionsFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
actions []*models.Action
|
|
err error
|
|
)
|
|
planIDString := r.URL.Query().Get("plan_id")
|
|
if planIDString == "" {
|
|
actions, err = m.Actions()
|
|
} else {
|
|
planID, convErr := strconv.ParseInt(planIDString, 10, 64)
|
|
if convErr != nil {
|
|
actions = []*models.Action{}
|
|
err = nil
|
|
} else {
|
|
plan := &models.Plan{PlanID: planID}
|
|
actions, err = m.GetActions(plan)
|
|
}
|
|
}
|
|
if err != nil {
|
|
serverError(w, err)
|
|
return
|
|
}
|
|
w.Header().Add("Content-Type", "application/json")
|
|
if err := json.NewEncoder(w).Encode(actions); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getActionByIDFunc(m *models.Model) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(chi.URLParam(r, "actionid"))
|
|
if err != nil {
|
|
notFoundHandler(w, r)
|
|
return
|
|
}
|
|
action, err := m.Action(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(action); err != nil {
|
|
serverError(w, err)
|
|
}
|
|
}
|
|
}
|