Пример #1
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
	}
}
Пример #2
0
func main() {
	app := new(bear.App)

	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		views.Error(w, 404, "not_found", models.NewPageCtx(r))
	})

	app.Use(Logger)
	app.Use(NotFound(handler))
	app.Use(FileServer(http.Dir("./public")))
	app.Use(BodyParser)

	app.ListenAndServe(":8080", routes.Mux())
}