//UpdateCategoryFunc is used to update a task, handes "/upd-category/" URL func UpdateCategoryFunc(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var redirectURL string r.ParseForm() oldName := r.URL.Path[len("/upd-category/"):] newName := r.Form.Get("catname") err := db.UpdateCategoryByName(oldName, newName) if err != nil { message = "error updating category" log.Println("not updated category " + oldName) redirectURL = "/category/" + oldName } else { message = "cat " + oldName + " -> " + newName redirectURL = "/category/" + newName } log.Println("redirecting to " + redirectURL) http.Redirect(w, r, redirectURL, http.StatusFound) } }
//UpdateCategoryFuncAPI will update the category for the user func UpdateCategoryFuncAPI(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var statusCode int var err error var message string var catErr bool var status types.Status token := r.Header["Token"][0] w.Header().Set("Content-Type", "application/json; charset=UTF-8") IsTokenValid, username := ValidateToken(token) //When the token is not valid show the default error JSON document if !IsTokenValid { status = types.Status{StatusCode: http.StatusInternalServerError, Message: message} w.WriteHeader(http.StatusInternalServerError) err = json.NewEncoder(w).Encode(status) if err != nil { panic(err) } return } log.Println("token is valid " + username + " is logged in") r.ParseForm() oldName := r.URL.Path[len("/api/update-category/"):] oldName = strings.Trim(oldName, "/") newName := r.Form.Get("catname") if strings.Trim(newName, " ") != "" { err = db.UpdateCategoryByName(username, oldName, newName) if err != nil { catErr = true } catErr = false } else { catErr = true } if catErr { statusCode = http.StatusInternalServerError message = "unable to update category from " + oldName + " to " + newName } else { statusCode = http.StatusOK message = "updated category from " + oldName + " to " + newName } status = types.Status{StatusCode: statusCode, Message: message} w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) err = json.NewEncoder(w).Encode(status) if err != nil { panic(err) } } }