package handlers import ( "net/http" "shop/internal/auth" ) type AccountHandler struct { pages *Pages auth *auth.Service } func NewAccountHandler(pages *Pages, authSvc *auth.Service) *AccountHandler { return &AccountHandler{pages: pages, auth: authSvc} } type accountPageData struct { Layout Name string } func (h *AccountHandler) Account(w http.ResponseWriter, r *http.Request) { user, err := h.auth.UserFromRequest(r.Context(), r) if err != nil || user == nil { http.Redirect(w, r, "/login?next=/account", http.StatusSeeOther) return } switch r.Method { case http.MethodGet: data := accountPageData{ Layout: h.pages.layout(r, "Личный кабинет", "account"), Name: user.Name, } data.Success = flashMsg(r, "ok") h.pages.render(w, "account.html", data) case http.MethodPost: h.updateProfile(w, r) default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (h *AccountHandler) updateProfile(w http.ResponseWriter, r *http.Request) { user, _ := h.auth.UserFromRequest(r.Context(), r) if user == nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return } if err := r.ParseForm(); err != nil { http.Redirect(w, r, "/account", http.StatusSeeOther) return } name := r.FormValue("name") if err := h.auth.UpdateName(r.Context(), user.ID, name); err != nil { data := accountPageData{ Layout: h.pages.layout(r, "Личный кабинет", "account"), Name: name, } data.Error = err.Error() h.pages.render(w, "account.html", data) return } http.Redirect(w, r, "/account?ok=profile", http.StatusSeeOther) }