Andrea Fazzi 5 лет назад
Родитель
Сommit
95b694ba5a
1 измененных файлов с 22 добавлено и 23 удалено
  1. 22 23
      handlers/handlers.go

+ 22 - 23
handlers/handlers.go

@@ -1,6 +1,7 @@
 package handlers
 
 import (
+	"encoding/json"
 	"fmt"
 	"io/ioutil"
 	"log"
@@ -210,6 +211,7 @@ func post(w http.ResponseWriter, r *http.Request, model string, pattern PathPatt
 		} else if pattern.RedirectPattern != "" {
 			if id := mux.Vars(r)["id"]; id != "" {
 				modelId, _ := strconv.Atoi(id)
+				log.Println(model, modelId, pattern)
 				http.Redirect(w, r, pattern.RedirectPath(model, uint(modelId)), http.StatusSeeOther)
 			} else {
 				http.Redirect(w, r, pattern.RedirectPath(model, data.GetID()), http.StatusSeeOther)
@@ -222,13 +224,27 @@ func post(w http.ResponseWriter, r *http.Request, model string, pattern PathPatt
 
 }
 
+func delete(w http.ResponseWriter, r *http.Request, model string, pattern PathPattern) {
+	postFn, ok := orm.Post[pattern.Path(model)]
+	if !ok {
+		renderer.Render[r.URL.Query().Get("format")](w, r, fmt.Errorf("Can't find ORM function for path %s!", pattern.PathPattern))
+	}
+	_, err := postFn(mux.Vars(r), r)
+	if err != nil {
+		renderer.Render["html"](w, r, err)
+	} else {
+		var data struct {
+			RedirectUrl string `json:"redirect_url"`
+		}
+		data.RedirectUrl = pattern.RedirectPath(model)
+
+		w.Header().Set("Content-Type", "application/json")
+		json.NewEncoder(w).Encode(data)
+	}
+}
+
 func modelHandler(model string, pattern PathPattern) http.Handler {
 	fn := func(w http.ResponseWriter, r *http.Request) {
-		var (
-		// ok     bool
-		// postFn orm.PostFn
-		)
-
 		switch r.Method {
 
 		case "GET":
@@ -238,24 +254,7 @@ func modelHandler(model string, pattern PathPattern) http.Handler {
 			post(w, r, model, pattern)
 
 		case "DELETE":
-			post(w, r, model, pattern)
-			// postFn, ok = orm.Post[pattern.Path(model)]
-			// if !ok {
-			// 	renderer.Render[r.URL.Query().Get("format")](w, r, fmt.Errorf("Can't find ORM function for path %s!", pattern.PathPattern))
-			// }
-			// _, err := postFn(mux.Vars(r), r)
-			// if err != nil {
-			// 	renderer.Render["html"](w, r, err)
-			// } else {
-			// 	var data struct {
-			// 		RedirectUrl string `json:"redirect_url"`
-			// 	}
-			// 	data.RedirectUrl = pattern.RedirectPath(model)
-
-			// 	w.Header().Set("Content-Type", "application/json")
-			// 	json.NewEncoder(w).Encode(data)
-			// }
-
+			delete(w, r, model, pattern)
 		}
 	}