示例#1
0
//AddCategoryFuncAPI will add the category for the user
func AddCategoryFuncAPI(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		var err error
		var message string
		var status types.Status
		var statusCode int
		var categoryErr bool

		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()

		category := r.Form.Get("category")
		if strings.Trim(category, " ") != "" {
			log.Println("adding category")
			err := db.AddCategory(username, category)
			if err != nil {
				categoryErr = true
			} else {
				categoryErr = false
			}
		} else {
			categoryErr = true
		}

		if categoryErr {
			statusCode = http.StatusInternalServerError
			message = "error adding category" + category
		} else {
			statusCode = http.StatusOK
			message = "added category " + category
		}

		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)
		}
	}
}
示例#2
0
文件: addViews.go 项目: Skarlso/Tasks
//AddCategoryFunc used to add new categories to the database
func AddCategoryFunc(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	category := r.Form.Get("category")
	if category != "" {
		err := db.AddCategory(category)
		if err != nil {
			message = "Error adding category"
			http.Redirect(w, r, "/", http.StatusBadRequest)
		} else {
			message = "Added category"
			http.Redirect(w, r, "/", http.StatusFound)
		}
	}
}
示例#3
0
//AddCategoryFunc used to add new categories to the database
func AddCategoryFunc(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" { // We respond only to POST requests, redirect to home for others
		http.Redirect(w, r, "/", http.StatusBadRequest)
		return
	}

	r.ParseForm()
	category := r.Form.Get("category")
	if strings.Trim(category, " ") != "" {
		username := sessions.GetCurrentUserName(r)
		log.Println("adding category")
		err := db.AddCategory(username, category)
		if err != nil {
			message = "Error adding category"
			http.Redirect(w, r, "/", http.StatusBadRequest)
		} else {
			message = "Added category"
			http.Redirect(w, r, "/", http.StatusFound)
		}
	}
}