初始化

This commit is contained in:
2024-07-09 13:12:31 +08:00
parent 8af343c842
commit 4dde1ffc8d
45 changed files with 2469 additions and 1 deletions
+5
View File
@@ -0,0 +1,5 @@
package controller
// Api api接口
type Api struct {
}
+43
View File
@@ -0,0 +1,43 @@
package exception
import (
"github.com/gin-gonic/gin"
"hepa-calc-api/consts"
"log"
"net/http"
"runtime/debug"
)
// Recover
// @Description: 处理全局异常
// @return gin.HandlerFunc
func Recover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// 打印错误堆栈信息
log.Printf("panic: %v\n", r)
debug.PrintStack()
c.JSON(http.StatusInternalServerError, gin.H{
"code": consts.ServerError,
"message": errorToString(r),
"data": "",
})
// 终止后续接口调用,不加的话recover到异常后,还会继续执行接口里后续代码
c.Abort()
}
}()
// 加载完 defer recover,继续后续接口调用
c.Next()
}
}
// recover错误,转string
func errorToString(r interface{}) string {
switch v := r.(type) {
case error:
return v.Error()
default:
return r.(string)
}
}
+53
View File
@@ -0,0 +1,53 @@
package middlewares
import (
"github.com/gin-gonic/gin"
)
// Auth Auth认证
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
//// 获取用户id
//userId := c.GetInt64("UserId")
//if userId == 0 {
// responses.Fail(c)
// c.Abort()
// return
//}
//
//// 获取用户数据
//adminUserDao := dao.AdminUserDao{}
//adminUser, err := adminUserDao.GetAdminUserFirstById(userId)
//if err != nil || adminUser == nil {
// responses.FailWithMessage("用户数据错误", c)
// c.Abort()
// return
//}
//
//if adminUser.Status == 2 {
// responses.FailWithMessage("用户审核中", c)
// c.Abort()
// return
//}
//
//if adminUser.Status == 3 {
// responses.FailWithMessage("用户已删除或禁用", c)
// c.Abort()
// return
//}
//
//if adminUser.IsDisabled == 1 {
// responses.FailWithMessage("用户已禁用", c)
// c.Abort()
// return
//}
//
//if adminUser.IsDeleted == 1 {
// responses.FailWithMessage("用户已删除", c)
// c.Abort()
// return
//}
c.Next()
}
}
+29
View File
@@ -0,0 +1,29 @@
package middlewares
import (
"github.com/gin-gonic/gin"
"net/http"
)
// Cors
// @Description: 跨域中间件
// @return gin.HandlerFunc
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "false")
c.Set("content-type", "application/json")
}
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
+72
View File
@@ -0,0 +1,72 @@
package middlewares
import (
"github.com/gin-gonic/gin"
"hepa-calc-api/consts"
"hepa-calc-api/global"
"hepa-calc-api/utils"
"net/http"
"strconv"
"strings"
)
// Jwt jwt认证
func Jwt() gin.HandlerFunc {
return func(c *gin.Context) {
authorization := c.Request.Header.Get("Authorization")
if authorization == "" || !strings.HasPrefix(authorization, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{
"message": "请求未授权",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 去除Bearer
authorization = authorization[7:] // 截取字符
// 检测是否存在黑名单
res, _ := global.Redis.Get(c, "jwt_black_"+authorization).Result()
if res != "" {
c.JSON(http.StatusOK, gin.H{
"message": "token错误/过期",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 解析jwt
t, err := utils.ParseJwt(authorization)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"message": "token错误/过期",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
// 转换类型
userId, err := strconv.ParseInt(t.UserId, 10, 64)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"message": "token错误",
"code": consts.TokenError,
"data": "",
})
c.Abort()
return
}
c.Set("UserId", userId) // 用户id
c.Next()
}
}
+60
View File
@@ -0,0 +1,60 @@
package middlewares
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"hepa-calc-api/global"
"time"
)
// Logrus 日志中间件
func Logrus() gin.HandlerFunc {
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 获取 请求 参数
params := make(map[string]string)
paramsRaw, ok := c.Get("params")
if ok {
requestParams, ok := paramsRaw.(map[string]string)
if ok || len(requestParams) > 0 {
params = requestParams
}
}
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := fmt.Sprintf("%6v", endTime.Sub(startTime))
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
// 日志格式
global.Logger.WithFields(logrus.Fields{
"http_status": statusCode,
"total_time": latencyTime,
"ip": clientIP,
"method": reqMethod,
"uri": reqUri,
"params": params,
}).Info("access")
}
}
@@ -0,0 +1,92 @@
package middlewares
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"hepa-calc-api/consts"
"io"
"net/http"
)
// RequestParamsMiddleware 获取请求参数中间件
func RequestParamsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
contentType := c.Request.Header.Get("Content-Type")
params := make(map[string]string)
// 判断请求参数类型
switch contentType {
case "application/json":
// 解析 application/json 请求体
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read request body"})
c.Abort()
return
}
// 创建新的请求对象,并设置请求体数据
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
var jsonParams map[string]interface{}
err = json.Unmarshal(bodyBytes, &jsonParams)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid JSON data",
"code": consts.HttpError,
"data": "",
})
c.Abort()
return
}
for key, value := range jsonParams {
params[key] = fmt.Sprintf("%v", value)
}
// 存储参数到上下文
c.Set("params", params)
case "multipart/form-data", "application/form-data", "application/x-www-form-urlencoded":
// 解析 Form 表单参数
err := c.Request.ParseForm()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid form data",
"code": consts.HttpError,
"data": "",
})
c.Abort()
return
}
for key, values := range c.Request.Form {
if len(values) > 0 {
params[key] = fmt.Sprintf("%v", values[0])
}
}
// 存储参数到上下文
c.Set("params", params)
default:
// 解析 URL 参数
queryParams := c.Request.URL.Query()
for key, values := range queryParams {
if len(values) > 0 {
params[key] = fmt.Sprintf("%v", values[0])
}
}
// 存储参数到上下文
c.Set("params", params)
}
// 继续处理请求
c.Next()
}
}
+87
View File
@@ -0,0 +1,87 @@
package model
import (
"database/sql/driver"
"errors"
"fmt"
"gorm.io/gorm"
"strings"
"time"
)
type Model struct {
CreatedAt LocalTime `gorm:"column:created_at;type:datetime;comment:创建时间" json:"created_at"`
UpdatedAt LocalTime `gorm:"column:updated_at;type:datetime;comment:修改时间" json:"updated_at"`
}
// LocalTime 自定义数据类型
type LocalTime time.Time
func (t *LocalTime) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var err error
// 前端接收的时间字符串
str := string(data)
// 去除接收的str收尾多余的"
timeStr := strings.Trim(str, "\"")
t1, err := time.Parse("2006-01-02 15:04:05", timeStr)
*t = LocalTime(t1)
return err
}
func (t LocalTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%v\"", time.Time(t).Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
func (t LocalTime) Value() (driver.Value, error) {
// MyTime 转换成 time.Time 类型
tTime := time.Time(t)
return tTime.Format("2006-01-02 15:04:05"), nil
}
func (t *LocalTime) Scan(v interface{}) error {
switch vt := v.(type) {
case time.Time:
// 字符串转成 time.Time 类型
*t = LocalTime(vt)
default:
return errors.New("类型处理错误")
}
return nil
}
func (t *LocalTime) String() string {
return fmt.Sprintf("hhh:%s", time.Time(*t).String())
}
func (t *LocalTime) IsEmpty() bool {
return time.Time(*t).IsZero()
}
func (m *Model) BeforeUpdate(tx *gorm.DB) (err error) {
m.UpdatedAt = LocalTime(time.Now())
tx.Statement.SetColumn("UpdatedAt", m.UpdatedAt)
return nil
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
if page <= 0 {
page = 1
}
switch {
case pageSize > 100:
pageSize = 100
case pageSize <= 0:
pageSize = 10
}
offset := (page - 1) * pageSize
return db.Offset(offset).Limit(pageSize)
}
}
+4
View File
@@ -0,0 +1,4 @@
package requests
type Requests struct {
}
+52
View File
@@ -0,0 +1,52 @@
package responses
import (
"github.com/gin-gonic/gin"
"knowledge/consts"
"net/http"
)
type res struct {
Code int `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
func result(code int, data interface{}, msg string, c *gin.Context) {
if data == nil {
data = gin.H{}
}
c.JSON(http.StatusOK, res{
code,
data,
msg,
})
}
func Ok(c *gin.Context) {
result(consts.HttpSuccess, map[string]interface{}{}, "成功", c)
}
func OkWithMessage(message string, c *gin.Context) {
result(consts.HttpSuccess, map[string]interface{}{}, message, c)
}
func OkWithData(data interface{}, c *gin.Context) {
result(consts.HttpSuccess, data, "成功", c)
}
func OkWithDetailed(data interface{}, message string, c *gin.Context) {
result(consts.HttpSuccess, data, message, c)
}
func Fail(c *gin.Context) {
result(consts.HttpError, map[string]interface{}{}, "失败", c)
}
func FailWithMessage(message string, c *gin.Context) {
result(consts.HttpError, map[string]interface{}{}, message, c)
}
func FailWithDetailed(data interface{}, message string, c *gin.Context) {
result(consts.HttpError, data, message, c)
}
+91
View File
@@ -0,0 +1,91 @@
package router
import (
"fmt"
"github.com/gin-gonic/gin"
"hepa-calc-api/api/controller"
"hepa-calc-api/api/exception"
"hepa-calc-api/api/middlewares"
"hepa-calc-api/config"
"hepa-calc-api/consts"
"net/http"
)
// Init 初始化路由
func Init() *gin.Engine {
r := gin.New()
// 环境设置
if config.C.Env == "prod" {
gin.SetMode(gin.ReleaseMode)
}
// 获取请求参数中间件-json格式下会导致接口获取不到请求数据
r.Use(middlewares.RequestParamsMiddleware())
// 日志中间件
r.Use(middlewares.Logrus())
// 异常
r.Use(gin.Recovery())
// 404处理
r.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
method := c.Request.Method
c.JSON(http.StatusNotFound, gin.H{
"msg": fmt.Sprintf("%s %s not found", method, path),
"code": consts.ClientHttpNotFound,
"data": "",
})
})
// 异常处理
r.Use(exception.Recover())
// 跨域处理
r.Use(middlewares.Cors())
// 加载基础路由
api := controller.Api{}
// 公开路由-不验证权限
publicRouter(r, api)
// 验证jwt
r.Use(middlewares.Jwt())
// 验证权限
r.Use(middlewares.Auth())
// 私有路由-验证权限
privateRouter(r, api)
// 公共路由-验证权限
adminRouter(r, api)
// 基础数据-验证权限
basicRouter(r, api)
return r
}
// publicRouter 公开路由-不验证权限
func publicRouter(r *gin.Engine, api controller.Api) {
}
// adminRouter 公共路由-验证权限
func adminRouter(r *gin.Engine, api controller.Api) {
}
// basicRouter 基础数据-验证权限
func basicRouter(r *gin.Engine, api controller.Api) {
}
// privateRouter 私有路由-验证权限
func privateRouter(r *gin.Engine, api controller.Api) {
}