Skip to content

Commit

Permalink
Refactor frontend build process in makefile and add fly deployment co…
Browse files Browse the repository at this point in the history
…mmand
  • Loading branch information
xijaja committed Dec 2, 2024
1 parent d1ffc37 commit a4cf41d
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 94 deletions.
46 changes: 17 additions & 29 deletions apis/handler/todo.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package handler
import (
"github.com/gofiber/fiber/v2"
"gone/database/model"
"gone/internal/code"
"gone/internal/result"
"gone/pkg/utils"
"log"
)

// 待办事项管理
Expand All @@ -13,9 +15,8 @@ type Todo struct{}
func (t *Todo) GetAllTodos(c *fiber.Ctx) error {
var todos model.Todos
var data = todos.FindAll()
return c.Status(fiber.StatusOK).JSON(code.Oka.Reveal(fiber.Map{
"list": data,
}))
log.Println("data:", data)
return c.JSON(result.Success("获取全部 todos 成功").WithData(fiber.Map{"list": data}))
}

// 更新或添加
Expand All @@ -29,29 +30,23 @@ func (t *Todo) UpdateOrAddTodo(c *fiber.Ctx) error {
// 绑定请求参数
_ = c.BodyParser(&req)
// 验证请求参数
if errs := code.Validator(req); errs != nil {
return c.Status(fiber.StatusOK).JSON(code.Bad.Reveal(fiber.Map{"failed": errs}))
if errs := utils.Validator(req); errs != nil {
return c.JSON(result.Error("请求参数错误").WithData(fiber.Map{"failed": errs}))
}
// 更新
if req.Id != 0 {
var todo model.Todos
var todo model.Todos
if req.Id > 0 {
todo.FindOne(req.Id)
todo.Title = req.Title
todo.Done = req.Done
todo.UpdateOne(req.Id)
return c.Status(fiber.StatusOK).JSON(code.Oka.Reveal(fiber.Map{
"msg": "更新 todo 成功",
}))
}
// 添加
todo := model.Todos{
Title: req.Title,
Done: req.Done,
return c.JSON(result.Success("更新 todo 成功"))
}
log.Println("添加Todo")
todo.Title = req.Title
todo.Done = req.Done
todo.AddOne()
return c.Status(fiber.StatusOK).JSON(code.Oka.Reveal(fiber.Map{
"msg": "添加 todo 成功",
}))
return c.JSON(result.Success("添加 todo 成功"))
}

// 删除待办事项
Expand All @@ -64,21 +59,14 @@ func (t *Todo) DeleteTodo(c *fiber.Ctx) error {
idInt = idInt*10 + int(v-'0')
}
if idInt == 0 {
return c.Status(fiber.StatusOK).JSON(code.Bad.Reveal(fiber.Map{
"msg": "id 参数有误或为空",
}))
return c.JSON(result.Error("id 参数有误或为空"))
}
var todo model.Todos
todo.DeleteOne(idInt)

return c.Status(fiber.StatusOK).JSON(code.Oka.Reveal(fiber.Map{
"msg": "成功删除待办",
}))
return c.JSON(result.Success("成功删除待办"))
}

// 完成待办事项
func (t *Todo) DoneTodo(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(code.Oka.Reveal(fiber.Map{
"msg": "该接口尚未完善",
}))
return c.JSON(result.Success("该接口尚未完善"))
}
34 changes: 15 additions & 19 deletions apis/handler/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"gone/apis/middleware"
"gone/database/dao"
"gone/database/model"
"gone/internal/code"
"gone/internal/result"
"gone/pkg/utils"
"gorm.io/gorm"
)
Expand All @@ -25,30 +25,28 @@ func (u *User) Login(c *fiber.Ctx) error {
}{}
// 绑定请求参数
_ = c.BodyParser(&req)
errs := code.Validator(req) // 验证请求参数
errs := utils.Validator(req) // 验证请求参数
if errs != nil {
return c.Status(fiber.StatusBadRequest).JSON(code.Bad.Reveal(fiber.Map{
"failed": errs,
}))
return c.JSON(result.Error("请求参数错误").WithData(fiber.Map{"failed": errs}))
}
// 查询用户是否存在
var user model.User
result := user.FindOneByUsername(req.Username)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return c.JSON(code.Bad.Reveal(fiber.Map{"msg": "用户不存在"}))
UserResult := user.FindOneByUsername(req.Username)
if errors.Is(UserResult.Error, gorm.ErrRecordNotFound) {
return c.JSON(result.Error("用户不存在"))
}
// 验证密码是否正确
if utils.MakeMd5(req.Password) != user.Password {
return c.JSON(code.Bad.Reveal(fiber.Map{"msg": "用户或密码错误"})) // 密码错误
return c.JSON(result.Error("用户或密码错误"))
}

// 生成新的 jwt
tokenValue, err := middleware.NewJWT(req.Username, string(user.Role), 3) // 生成签名字符串
if err != nil {
return c.JSON(code.Err.Reveal(fiber.Map{"msg": "生成 Token 失败"}))
return c.JSON(result.Error("生成 Token 失败"))
}
// 构建返回
return c.JSON(code.Oka.Reveal(fiber.Map{"msg": "登录成功", "token": tokenValue}))
return c.JSON(result.Success("登录成功").WithData(fiber.Map{"token": tokenValue}))
}

// Logout 登出
Expand All @@ -58,19 +56,17 @@ func (u *User) Logout(c *fiber.Ctx) error {
// 将 token 作废,保存到 redis 标记为无效
rds := dao.NewRedis(token) // 将 token 作为 redis 的 key,此处 key-value 同值
rds.SetRedisKey(token, 60*60*24*3) // 3 天后过期删除,覆盖原有的过期时间(可以通过计算设置为剩余时间,但没必要)
return c.JSON(code.Oka.Reveal(fiber.Map{"msg": "登出成功"}))
return c.JSON(result.Success("登出成功"))
}

// 做点什么
func (u *User) PostSth(c *fiber.Ctx) error {
// 从上下文 jwk 中获取 jwt
user := c.Locals("user").(*jwt.Token) // 获取 jwt, user 是 jwt 的默认载荷名称
// 构建返回
return c.Status(fiber.StatusOK).JSON(
code.Oka.Reveal(fiber.Map{
"username": user.Claims.(jwt.MapClaims)["username"], // 获取载荷中的 username
"role": user.Claims.(jwt.MapClaims)["role"], // 获取载荷中的 role
"json_web_token": user.Raw, // 获取载荷中的 json_web_token
}),
)
return c.JSON(result.Success("登出成功").WithData(fiber.Map{
"username": user.Claims.(jwt.MapClaims)["username"], // 获取载荷中的 username
"role": user.Claims.(jwt.MapClaims)["role"], // 获取载荷中的 role
"json_web_token": user.Raw, // 获取载荷中的 json_web_token
}))
}
10 changes: 5 additions & 5 deletions apis/middleware/jwk.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/golang-jwt/jwt/v4"
"gone/config"
"gone/database/dao"
"gone/internal/code"
"gone/internal/result"
"strings"
"time"
)
Expand Down Expand Up @@ -49,25 +49,25 @@ func success(c *fiber.Ctx) error {
rds := dao.NewRedis(token.Raw)
// 如果返回值为 1 则表示该 token 存在于黑名单之中
if haveField := rds.IsRedisKey(); haveField == 1 {
return c.Status(fiber.StatusUnauthorized).JSON(code.Red.Reveal(fiber.Map{"msg": "Token 已过期,请重新登录"}))
return c.JSON(result.NoPermission("Token 已过期,请重新登录"))
}
// 自动续期
// 如果 token 的有效期小于 7 天,则修改 token 的有效期加 1 天
nowTime := time.Now().Unix()
if token.Valid && token.Claims.(jwt.MapClaims)["exp"].(float64)-float64(nowTime) < float64(60*60*24*7) {
token.Claims.(jwt.MapClaims)["exp"] = time.Now().Add(time.Hour * 24).Unix()
} else {
return c.JSON(code.Red.Reveal(fiber.Map{"msg": "登录过期"}))
return c.JSON(result.NoPermission("登录过期"))
}
return c.Next()
}

// 用于处理错误的函数
func jwtError(c *fiber.Ctx, err error) error {
if err.Error() == "Missing or malformed JWT" {
return c.Status(fiber.StatusBadRequest).JSON(code.Red.Reveal(fiber.Map{"msg": "缺少 Token 或格式错误"}))
return c.JSON(result.Error("缺少 Token 或格式错误"))
}
return c.Status(fiber.StatusUnauthorized).JSON(code.Red.Reveal(fiber.Map{"msg": "无效或过期的 Token"}))
return c.JSON(result.NoPermission("无效或过期的 Token"))
}

// 用于解密验证的函数
Expand Down
7 changes: 4 additions & 3 deletions database/model/todos_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ func (t *Todos) TableName() string {
}

// AddOne 添加一条数据
func (t *Todos) AddOne() *Todos {
db.Create(&t)
return t
func (t *Todos) AddOne() {
// db.Create(&t)
// 使用原生语句创建
db.Exec("INSERT INTO todos (title, done) VALUES (?, ?)", t.Title, t.Done)
}

// FindOne 查询一条数据
Expand Down
34 changes: 0 additions & 34 deletions internal/code/codes.go

This file was deleted.

2 changes: 1 addition & 1 deletion pkg/utils/request.go → internal/result/request.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utils
package result

import (
"bytes"
Expand Down
53 changes: 53 additions & 0 deletions internal/result/response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package result

import (
"github.com/gofiber/fiber/v2"
)

// Res 响应结构体
type Res struct {
Code uint `json:"code"`
Msg string `json:"msg"`
Data fiber.Map `json:"data"`
}

// 请求成功
func Success(msg ...string) *Res {
if len(msg) > 0 {
return &Res{2000, msg[0], fiber.Map{}}
}
return &Res{2000, "success", fiber.Map{}}
}

// 请求错误
func Error(msg ...string) *Res {
if len(msg) > 0 {
return &Res{4000, msg[0], fiber.Map{}}
}
return &Res{4000, "error", fiber.Map{}}
}

// 无权限
func NoPermission(msg ...string) *Res {
if len(msg) > 0 {
return &Res{4001, msg[0], fiber.Map{}}
}
return &Res{4001, "no permission", fiber.Map{}}
}

// 系统异常
func SystemError(msg ...string) *Res {
if len(msg) > 0 {
return &Res{5000, msg[0], fiber.Map{}}
}
return &Res{5000, "system error", fiber.Map{}}
}

// WithData 设置响应数据
func (r Res) WithData(data fiber.Map) *Res {
return &Res{
Code: r.Code,
Msg: r.Msg,
Data: data,
}
}
1 change: 1 addition & 0 deletions makefile
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ help:
@echo "可用的命令:"
@echo " make pg - 启动本地的 postgres 数据库"
@echo " make rs - 启动本地的 redis 数据库"
@echo " make fly - 部署到 fly.io"
@echo " make frontend - 构建前端项目"
@echo " make build - 构建 Docker 镜像"
@echo " make save - 保存并传输镜像到远程主机"
Expand Down
5 changes: 2 additions & 3 deletions internal/code/validator.go → pkg/utils/validator.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package code
package utils

import (
"fmt"
"github.com/go-playground/validator/v10"
"gone/pkg/utils"
"log"
)

Expand All @@ -23,7 +22,7 @@ func Validator(st interface{}) []*ErrorResponse {
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
var element ErrorResponse
element.Field = utils.CamelToSnake(err.StructNamespace())
element.Field = CamelToSnake(err.StructNamespace())
element.Tag = err.Tag()
element.Value = err.Param()
element.ErrorMsg = validatorErrorMsgMaker(element.Field, element.Tag, element.Value)
Expand Down

0 comments on commit a4cf41d

Please sign in to comment.