package pkg import ( "context" "net/http" ) type LanguageOption struct { Tag string Name string } type ProfilePage struct { Title string Name string Email string Password string PasswordConfirm string Language string Languages []LanguageOption } func ProfileHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user := getUser(r) if !user.LoggedIn { http.Redirect(w, r, "/login", http.StatusUnauthorized) return } conn := getConn(r) locale := getLocale(r) page := ProfilePage{ Title: pgettext("title", "User Settings", locale), Email: user.Email, Language: user.Language.String(), } if r.Method == "POST" { r.ParseForm() page.Email = r.FormValue("email") page.Name = r.FormValue("name") page.Password = r.FormValue("password") page.PasswordConfirm = r.FormValue("password_confirm") page.Language = r.FormValue("language") cookie := conn.MustGetText(r.Context(), "", "update user_profile set name = $1, email = $2, lang_tag = $3 returning build_cookie()", page.Name, page.Email, page.Language) setSessionCookie(w, cookie) http.Redirect(w, r, "/profile", http.StatusSeeOther) return } else { page.Languages = mustGetLanguageOptions(r.Context(), conn) if err := conn.QueryRow(r.Context(), "select name from user_profile").Scan(&page.Name); err != nil { panic(nil) } } mustRenderAppTemplate(w, r, "profile.html", page) }) } func mustGetLanguageOptions(ctx context.Context, conn *Conn) []LanguageOption { rows, err := conn.Query(ctx, "select lang_tag, endonym from language where selectable") if err != nil { panic(err) } defer rows.Close() var langs []LanguageOption for rows.Next() { var lang LanguageOption err = rows.Scan(&lang.Tag, &lang.Name) if err != nil { panic(err) } langs = append(langs, lang) } if rows.Err() != nil { panic(rows.Err()) } return langs }