Beispiel #1
0
// HTMLForUser writes a specified view with user model to the response.
func HTMLForUser(w http.ResponseWriter, r *http.Request, view string) {
	vars := mux.Vars(r)
	id, err := strconv.Atoi(vars["id"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	user := &models.User{ID: uint64(id)}
	err = models.DB.Read(user)
	if err != nil {
		if err == sql.ErrNoRows {
			return
		}

		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	flashes, err := Flashes(w, r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	views.HTML(w, view, models.NewUserCtx(r, user, nil, flashes))
}
Beispiel #2
0
func (_ User) Create(w http.ResponseWriter, r *http.Request) {
	user := new(models.User)
	if err := models.Decoder.Decode(user, r.PostForm); err != nil {
		ctx := models.NewUserCtx(r, user, []string{"bad request"}, nil)
		views.Error(w, http.StatusBadRequest, "user_new", ctx)
		return
	}

	id, err := models.DB.WithCreate(user).Exec()
	if err != nil {
		if verr, ok := err.(models.ValidationError); ok {
			views.Error(w, 422, "user_new", models.NewUserCtx(r, user, verr, nil))
			return
		}

		if perr, ok := err.(*pq.Error); ok && perr.Code.Class() == "23" {
			ctx := models.NewUserCtx(r, user, []string{"email is taken"}, nil)
			views.Error(w, http.StatusConflict, "user_new", ctx)
			return
		}

		log.Println(err)
	}

	user.ID = id
	if err := Remember(w, r, user); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := AddFlash(w, r, fmt.Sprintf("welcome %s!", user.Name)); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := Redirect(w, r, "user:show", "id", strconv.Itoa(int(id))); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Beispiel #3
0
func (_ User) New(w http.ResponseWriter, r *http.Request) {
	views.HTML(w, "user_new", models.NewUserCtx(r, new(models.User), nil, nil))
}