render html change templ

This commit is contained in:
2024-12-11 17:11:53 +08:00
parent cff64975d7
commit e9876b0c6f
65 changed files with 1548 additions and 475 deletions

172
internal/handler/account.go Normal file
View File

@@ -0,0 +1,172 @@
package handler
import (
"database/sql"
"net/http"
"time"
"github.com/google/uuid"
"github.com/zhang2092/go-url-shortener/internal/db"
"github.com/zhang2092/go-url-shortener/internal/middleware"
"github.com/zhang2092/go-url-shortener/internal/pkg/cookie"
pwd "github.com/zhang2092/go-url-shortener/internal/pkg/password"
"github.com/zhang2092/go-url-shortener/internal/templ"
"github.com/zhang2092/go-url-shortener/internal/templ/model"
)
func RegisterView(w http.ResponseWriter, r *http.Request) {
templ.Register(w, r, &model.RegisterPageData{})
}
func Register(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
email := r.PostFormValue("email")
username := r.PostFormValue("username")
password := r.PostFormValue("password")
resp, ok := viladatorRegister(email, username, password)
if !ok {
templ.Register(w, r, resp)
return
}
hashedPassword, err := pwd.BcryptHashPassword(password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
arg := &db.CreateUserParams{
ID: uuid.Must(uuid.NewRandom()).String(),
Username: username,
HashedPassword: hashedPassword,
Email: email,
}
_, err = store.CreateUser(r.Context(), arg)
if err != nil {
if store.IsUniqueViolation(err) {
resp.Summary = "邮箱或名称已经存在"
templ.Register(w, r, resp)
return
}
resp.Summary = "请求网络错误,请刷新重试"
templ.Register(w, r, resp)
return
}
http.Redirect(w, r, "/login", http.StatusFound)
}
}
func LoginView(w http.ResponseWriter, r *http.Request) {
templ.Login(w, r, &model.LoginPageData{})
}
func Login(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if err := r.ParseForm(); err != nil {
templ.Login(w, r, &model.LoginPageData{Summary: "请求网络错误,请刷新重试"})
return
}
email := r.PostFormValue("email")
password := r.PostFormValue("password")
resp, ok := viladatorLogin(email, password)
if !ok {
templ.Login(w, r, resp)
return
}
ctx := r.Context()
user, err := store.GetUserByEmail(ctx, email)
if err != nil {
if store.IsNoRows(sql.ErrNoRows) {
resp.Summary = "邮箱或密码错误"
templ.Login(w, r, resp)
return
}
resp.Summary = "请求网络错误,请刷新重试"
templ.Login(w, r, resp)
return
}
err = pwd.BcryptComparePassword(user.HashedPassword, password)
if err != nil {
resp.Summary = "邮箱或密码错误"
templ.Login(w, r, resp)
return
}
encoded, err := middleware.Encode(middleware.AuthorizeCookie, &middleware.Authorize{ID: user.ID, Name: user.Username})
if err != nil {
resp.Summary = "请求网络错误,请刷新重试(cookie)"
templ.Login(w, r, resp)
return
}
c := cookie.NewCookie(cookie.AuthorizeName, encoded, time.Now().Add(time.Duration(7200)*time.Second))
http.SetCookie(w, c)
http.Redirect(w, r, "/", http.StatusFound)
}
}
func Logout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cookie.DeleteCookie(w, cookie.AuthorizeName)
http.Redirect(w, r, "/login", http.StatusFound)
}
}
func viladatorRegister(email, username, password string) (*model.RegisterPageData, bool) {
ok := true
resp := &model.RegisterPageData{
Email: email,
Username: username,
Password: password,
}
if !ValidateRxEmail(email) {
resp.EmailMsg = "请填写正确的邮箱地址"
ok = false
}
if !ValidateRxUsername(username) {
resp.UsernameMsg = "名称(6-20,字母,数字)"
ok = false
}
if !ValidatePassword(password) {
resp.PasswordMsg = "密码(8-20位)"
ok = false
}
return resp, ok
}
func viladatorLogin(email, password string) (*model.LoginPageData, bool) {
ok := true
errs := &model.LoginPageData{
Email: email,
Password: password,
}
if !ValidateRxEmail(email) {
errs.EmailMsg = "请填写正确的邮箱地址"
ok = false
}
if len(password) == 0 {
errs.PasswordMsg = "请填写正确的密码"
ok = false
}
return errs, ok
}

22
internal/handler/home.go Normal file
View File

@@ -0,0 +1,22 @@
package handler
import (
"net/http"
"github.com/zhang2092/go-url-shortener/internal/db"
"github.com/zhang2092/go-url-shortener/internal/middleware"
"github.com/zhang2092/go-url-shortener/internal/templ"
)
func HomeView(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := middleware.GetUser(ctx)
result, err := store.ListUrlByUser(ctx, user.ID)
if err != nil {
templ.Home(w, r, nil)
return
}
templ.Home(w, r, result)
}
}

55
internal/handler/resp.go Normal file
View File

@@ -0,0 +1,55 @@
package handler
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
)
type response struct {
Success bool `json:"success"`
Message string `json:"message"`
Data any `json:"data"`
}
func respond(w http.ResponseWriter, message string, v any, statusCode int) {
rsp := response{
Success: true,
Message: message,
Data: v,
}
b, err := json.Marshal(rsp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
_, err = w.Write(b)
if err != nil && !errors.Is(err, context.Canceled) {
log.Printf("could not write http response: %v\n", err)
}
}
func RespondErr(w http.ResponseWriter, message string, v any) {
rsp := response{
Success: false,
Message: message,
Data: v,
}
b, err := json.Marshal(rsp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
_, err = w.Write(b)
if err != nil && !errors.Is(err, context.Canceled) {
log.Printf("could not write http response: %v\n", err)
}
}

View File

@@ -0,0 +1,90 @@
package handler
import (
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/zhang2092/go-url-shortener/internal/db"
"github.com/zhang2092/go-url-shortener/internal/middleware"
"github.com/zhang2092/go-url-shortener/internal/service"
"github.com/zhang2092/go-url-shortener/internal/shortener"
"github.com/zhang2092/go-url-shortener/internal/templ"
)
func CreateShortUrlView(w http.ResponseWriter, r *http.Request) {
templ.CreateUrl(w, r, "")
}
func CreateShortUrl(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if err := r.ParseForm(); err != nil {
templ.CreateUrl(w, r, "请求参数错误")
return
}
ctx := r.Context()
user := middleware.GetUser(ctx)
longUrl := r.PostFormValue("long_url")
shortUrl, err := shortener.GenerateShortLink(longUrl, user.ID)
if err != nil {
templ.CreateUrl(w, r, "生成短路径错误")
return
}
_, err = store.CreateUserUrl(ctx, &db.CreateUserUrlParams{
UserID: user.ID,
ShortUrl: shortUrl,
OriginUrl: longUrl,
ExpireAt: time.Now().Add(time.Hour * 6),
})
if err != nil {
templ.CreateUrl(w, r, "短路径存储错误")
return
}
err = service.SaveUrlMapping(shortUrl, longUrl, user.ID)
if err != nil {
templ.CreateUrl(w, r, "短路径存储错误")
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
}
func DeleteShortUrl(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
shorUrl := vars["shortUrl"]
_, err := store.UpdateStatus(r.Context(), &db.UpdateStatusParams{
ShortUrl: shorUrl,
Status: -1,
})
if err != nil {
RespondErr(w, "删除错误", nil)
return
}
err = service.DeleteShortUrl(shorUrl)
if err != nil {
RespondErr(w, "删除错误", nil)
return
}
respond(w, "删除成功", nil, http.StatusOK)
}
}
func HandleShortUrlRedirect(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
shorUrl := vars["shortUrl"]
link, err := service.RetrieveInitialUrl(shorUrl)
if err != nil || len(link) == 0 {
RespondErr(w, "短链已经失效", nil)
return
}
http.Redirect(w, r, link, http.StatusFound)
}

View File

@@ -0,0 +1,38 @@
package handler
import (
"regexp"
"strings"
)
var (
rxPhone = regexp.MustCompile(`^(13|14|15|16|17|18|19)\d{9}$`)
rxEmail = regexp.MustCompile(`\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`)
rxUsername = regexp.MustCompile(`^[a-z0-9A-Z]{6,20}$`) // 6到20位字母数字
// rxPassword = regexp.MustCompile(`^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{8,18}$`) // 最少6位包括至少1个大写字母1个小写字母1个数字1个特殊字符
)
func ValidateRxPhone(phone string) bool {
phone = strings.TrimSpace(phone)
return rxPhone.MatchString(phone)
}
func ValidateRxEmail(email string) bool {
email = strings.TrimSpace(email)
return rxEmail.MatchString(email)
}
func ValidateRxUsername(username string) bool {
username = strings.TrimSpace(username)
return rxUsername.MatchString(username)
}
// func ValidateRxPassword(password string) bool {
// password = strings.TrimSpace(password)
// return rxPassword.MatchString(password)
// }
func ValidatePassword(password string) bool {
password = strings.TrimSpace(password)
return len(password) >= 8 && len(password) <= 20
}