后端重构
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/service"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Api *api
|
||||
|
||||
type api struct {
|
||||
Info *InfoApi
|
||||
}
|
||||
|
||||
// NewApi 创建API实例
|
||||
func NewApi(db *gorm.DB) *api {
|
||||
svc := service.NewService(db)
|
||||
a := &api{
|
||||
Info: NewInfoApi(svc.Info),
|
||||
}
|
||||
Api = a
|
||||
return a
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/model"
|
||||
"kra/internal/plugin/announcement/model/request"
|
||||
"kra/internal/plugin/announcement/service"
|
||||
"kra/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// InfoApi 公告API
|
||||
type InfoApi struct {
|
||||
svc *service.Info
|
||||
}
|
||||
|
||||
// NewInfoApi 创建公告API
|
||||
func NewInfoApi(svc *service.Info) *InfoApi {
|
||||
return &InfoApi{svc: svc}
|
||||
}
|
||||
|
||||
// CreateInfo 创建公告
|
||||
// @Tags Info
|
||||
// @Summary 创建公告
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.Info true "创建公告"
|
||||
// @Success 200 {object} response.Response{msg=string} "创建成功"
|
||||
// @Router /info/createInfo [post]
|
||||
func (a *InfoApi) CreateInfo(c *gin.Context) {
|
||||
var infoData model.Info
|
||||
err := c.ShouldBindJSON(&infoData)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = a.svc.CreateInfo(&infoData)
|
||||
if err != nil {
|
||||
response.FailWithMessage("创建失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage("创建成功", c)
|
||||
}
|
||||
|
||||
// DeleteInfo 删除公告
|
||||
// @Tags Info
|
||||
// @Summary 删除公告
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.Info true "删除公告"
|
||||
// @Success 200 {object} response.Response{msg=string} "删除成功"
|
||||
// @Router /info/deleteInfo [delete]
|
||||
func (a *InfoApi) DeleteInfo(c *gin.Context) {
|
||||
ID := c.Query("ID")
|
||||
err := a.svc.DeleteInfo(ID)
|
||||
if err != nil {
|
||||
response.FailWithMessage("删除失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage("删除成功", c)
|
||||
}
|
||||
|
||||
// DeleteInfoByIds 批量删除公告
|
||||
// @Tags Info
|
||||
// @Summary 批量删除公告
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
|
||||
// @Router /info/deleteInfoByIds [delete]
|
||||
func (a *InfoApi) DeleteInfoByIds(c *gin.Context) {
|
||||
IDs := c.QueryArray("IDs[]")
|
||||
if err := a.svc.DeleteInfoByIds(IDs); err != nil {
|
||||
response.FailWithMessage("批量删除失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage("批量删除成功", c)
|
||||
}
|
||||
|
||||
// UpdateInfo 更新公告
|
||||
// @Tags Info
|
||||
// @Summary 更新公告
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data body model.Info true "更新公告"
|
||||
// @Success 200 {object} response.Response{msg=string} "更新成功"
|
||||
// @Router /info/updateInfo [put]
|
||||
func (a *InfoApi) UpdateInfo(c *gin.Context) {
|
||||
var infoData model.Info
|
||||
err := c.ShouldBindJSON(&infoData)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = a.svc.UpdateInfo(infoData)
|
||||
if err != nil {
|
||||
response.FailWithMessage("更新失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithMessage("更新成功", c)
|
||||
}
|
||||
|
||||
// FindInfo 用id查询公告
|
||||
// @Tags Info
|
||||
// @Summary 用id查询公告
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query model.Info true "用id查询公告"
|
||||
// @Success 200 {object} response.Response{data=model.Info,msg=string} "查询成功"
|
||||
// @Router /info/findInfo [get]
|
||||
func (a *InfoApi) FindInfo(c *gin.Context) {
|
||||
ID := c.Query("ID")
|
||||
reinfo, err := a.svc.GetInfo(ID)
|
||||
if err != nil {
|
||||
response.FailWithMessage("查询失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithData(reinfo, c)
|
||||
}
|
||||
|
||||
// GetInfoList 分页获取公告列表
|
||||
// @Tags Info
|
||||
// @Summary 分页获取公告列表
|
||||
// @Security ApiKeyAuth
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query request.InfoSearch true "分页获取公告列表"
|
||||
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
|
||||
// @Router /info/getInfoList [get]
|
||||
func (a *InfoApi) GetInfoList(c *gin.Context) {
|
||||
var pageInfo request.InfoSearch
|
||||
err := c.ShouldBindQuery(&pageInfo)
|
||||
if err != nil {
|
||||
response.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
list, total, err := a.svc.GetInfoInfoList(pageInfo)
|
||||
if err != nil {
|
||||
response.FailWithMessage("获取失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithDetailed(response.PageResult{
|
||||
List: list,
|
||||
Total: total,
|
||||
Page: pageInfo.Page,
|
||||
PageSize: pageInfo.PageSize,
|
||||
}, "获取成功", c)
|
||||
}
|
||||
|
||||
// GetInfoDataSource 获取Info的数据源
|
||||
// @Tags Info
|
||||
// @Summary 获取Info的数据源
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Success 200 {object} response.Response{data=object,msg=string} "查询成功"
|
||||
// @Router /info/getInfoDataSource [get]
|
||||
func (a *InfoApi) GetInfoDataSource(c *gin.Context) {
|
||||
// 此接口为获取数据源定义的数据
|
||||
dataSource, err := a.svc.GetInfoDataSource()
|
||||
if err != nil {
|
||||
response.FailWithMessage("查询失败", c)
|
||||
return
|
||||
}
|
||||
response.OkWithData(dataSource, c)
|
||||
}
|
||||
|
||||
// GetInfoPublic 不需要鉴权的公告接口
|
||||
// @Tags Info
|
||||
// @Summary 不需要鉴权的公告接口
|
||||
// @accept application/json
|
||||
// @Produce application/json
|
||||
// @Param data query request.InfoSearch true "分页获取公告列表"
|
||||
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
|
||||
// @Router /info/getInfoPublic [get]
|
||||
func (a *InfoApi) GetInfoPublic(c *gin.Context) {
|
||||
// 此接口不需要鉴权 示例为返回了一个固定的消息接口,一般本接口用于C端服务,需要自己实现业务逻辑
|
||||
response.OkWithDetailed(gin.H{"info": "不需要鉴权的公告接口信息"}, "获取成功", c)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package config
|
||||
|
||||
// Config 公告插件配置
|
||||
type Config struct {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package global
|
||||
|
||||
import "kra/internal/plugin/announcement/config"
|
||||
|
||||
var Config config.Config
|
||||
@@ -0,0 +1,51 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"kra/internal/data/model"
|
||||
"kra/internal/plugin/plugin-tool/utils"
|
||||
)
|
||||
|
||||
func Api(ctx context.Context, db *gorm.DB) {
|
||||
entities := []model.SysAPI{
|
||||
{
|
||||
Path: "/info/createInfo",
|
||||
Description: "新建公告",
|
||||
APIGroup: "公告",
|
||||
Method: "POST",
|
||||
},
|
||||
{
|
||||
Path: "/info/deleteInfo",
|
||||
Description: "删除公告",
|
||||
APIGroup: "公告",
|
||||
Method: "DELETE",
|
||||
},
|
||||
{
|
||||
Path: "/info/deleteInfoByIds",
|
||||
Description: "批量删除公告",
|
||||
APIGroup: "公告",
|
||||
Method: "DELETE",
|
||||
},
|
||||
{
|
||||
Path: "/info/updateInfo",
|
||||
Description: "更新公告",
|
||||
APIGroup: "公告",
|
||||
Method: "PUT",
|
||||
},
|
||||
{
|
||||
Path: "/info/findInfo",
|
||||
Description: "根据ID获取公告",
|
||||
APIGroup: "公告",
|
||||
Method: "GET",
|
||||
},
|
||||
{
|
||||
Path: "/info/getInfoList",
|
||||
Description: "获取公告列表",
|
||||
APIGroup: "公告",
|
||||
Method: "GET",
|
||||
},
|
||||
}
|
||||
utils.RegisterApis(db, entities...)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"kra/internal/plugin/announcement/model"
|
||||
)
|
||||
|
||||
func Gorm(ctx context.Context, db *gorm.DB) {
|
||||
err := db.WithContext(ctx).AutoMigrate(
|
||||
new(model.Info),
|
||||
)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "注册表失败!")
|
||||
zap.L().Error(fmt.Sprintf("%+v", err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"kra/internal/data/model"
|
||||
"kra/internal/plugin/plugin-tool/utils"
|
||||
)
|
||||
|
||||
func Menu(ctx context.Context, db *gorm.DB) {
|
||||
entities := []model.SysBaseMenu{
|
||||
{
|
||||
ParentID: 24,
|
||||
Path: "anInfo",
|
||||
Name: "anInfo",
|
||||
Hidden: false,
|
||||
Component: "plugin/announcement/view/info.vue",
|
||||
Sort: 5,
|
||||
Title: "公告管理",
|
||||
Icon: "box",
|
||||
},
|
||||
}
|
||||
utils.RegisterMenus(db, entities...)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/router"
|
||||
"kra/internal/server/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// RouterConfig 路由配置
|
||||
type RouterConfig struct {
|
||||
RouterPrefix string
|
||||
}
|
||||
|
||||
func Router(engine *gin.Engine, db *gorm.DB) {
|
||||
RouterWithConfig(engine, db, nil)
|
||||
}
|
||||
|
||||
func RouterWithConfig(engine *gin.Engine, db *gorm.DB, cfg *RouterConfig) {
|
||||
// 获取配置中的路由前缀
|
||||
routerPrefix := ""
|
||||
if cfg != nil {
|
||||
routerPrefix = cfg.RouterPrefix
|
||||
}
|
||||
|
||||
public := engine.Group(routerPrefix)
|
||||
private := engine.Group(routerPrefix)
|
||||
private.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
|
||||
|
||||
routerInstance := router.NewRouter(db)
|
||||
routerInstance.Info.Init(public, private)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/viper"
|
||||
"go.uber.org/zap"
|
||||
"kra/internal/plugin/announcement/global"
|
||||
)
|
||||
|
||||
func Viper(vp *viper.Viper) {
|
||||
err := vp.UnmarshalKey("announcement", &global.Config)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "初始化配置文件失败!")
|
||||
zap.L().Error(fmt.Sprintf("%+v", err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Info 公告 结构体
|
||||
type Info struct {
|
||||
ID uint `json:"ID" gorm:"primarykey"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
|
||||
Title string `json:"title" form:"title" gorm:"column:title;comment:公告标题;"` //标题
|
||||
Content string `json:"content" form:"content" gorm:"column:content;comment:公告内容;type:text;"` //内容
|
||||
UserID *int `json:"userID" form:"userID" gorm:"column:user_id;comment:发布者;"` //作者
|
||||
Attachments datatypes.JSON `json:"attachments" form:"attachments" gorm:"column:attachments;comment:相关附件;" swaggertype:"array,object"` //附件
|
||||
}
|
||||
|
||||
// TableName 公告 Info自定义表名 kra_announcements_info
|
||||
func (Info) TableName() string {
|
||||
return "kra_announcements_info"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// PageInfo 分页信息
|
||||
type PageInfo struct {
|
||||
Page int `json:"page" form:"page"`
|
||||
PageSize int `json:"pageSize" form:"pageSize"`
|
||||
Keyword string `json:"keyword" form:"keyword"`
|
||||
}
|
||||
|
||||
// InfoSearch 公告搜索请求
|
||||
type InfoSearch struct {
|
||||
StartCreatedAt *time.Time `json:"startCreatedAt" form:"startCreatedAt"`
|
||||
EndCreatedAt *time.Time `json:"endCreatedAt" form:"endCreatedAt"`
|
||||
PageInfo
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package announcement
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"kra/internal/plugin/announcement/initialize"
|
||||
interfaces "kra/pkg/utils/plugin/v2"
|
||||
)
|
||||
|
||||
var _ interfaces.Plugin = (*plugin)(nil)
|
||||
|
||||
var Plugin = new(plugin)
|
||||
|
||||
type plugin struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// SetDB 设置数据库连接
|
||||
func (p *plugin) SetDB(db *gorm.DB) {
|
||||
p.db = db
|
||||
}
|
||||
|
||||
func (p *plugin) Register(engine *gin.Engine) {
|
||||
ctx := context.Background()
|
||||
// 如果需要配置文件,请到config.Config中填充配置结构,且到下方发放中填入其在config.yaml中的key
|
||||
// initialize.Viper()
|
||||
// 安装插件时候自动注册的api数据请到下方法.Api方法中实现
|
||||
initialize.Api(ctx, p.db)
|
||||
// 安装插件时候自动注册的api数据请到下方法.Menu方法中实现
|
||||
initialize.Menu(ctx, p.db)
|
||||
initialize.Gorm(ctx, p.db)
|
||||
initialize.Router(engine, p.db)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/api"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Router *router
|
||||
|
||||
type router struct {
|
||||
Info *InfoRouter
|
||||
}
|
||||
|
||||
// NewRouter 创建路由实例
|
||||
func NewRouter(db *gorm.DB) *router {
|
||||
apiInstance := api.NewApi(db)
|
||||
r := &router{
|
||||
Info: NewInfoRouter(apiInstance.Info),
|
||||
}
|
||||
Router = r
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/api"
|
||||
"kra/internal/server/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// InfoRouter 公告路由
|
||||
type InfoRouter struct {
|
||||
apiInfo *api.InfoApi
|
||||
}
|
||||
|
||||
// NewInfoRouter 创建公告路由
|
||||
func NewInfoRouter(apiInfo *api.InfoApi) *InfoRouter {
|
||||
return &InfoRouter{apiInfo: apiInfo}
|
||||
}
|
||||
|
||||
// Init 初始化 公告 路由信息
|
||||
func (r *InfoRouter) Init(public *gin.RouterGroup, private *gin.RouterGroup) {
|
||||
{
|
||||
group := private.Group("info").Use(middleware.OperationRecord())
|
||||
group.POST("createInfo", r.apiInfo.CreateInfo) // 新建公告
|
||||
group.DELETE("deleteInfo", r.apiInfo.DeleteInfo) // 删除公告
|
||||
group.DELETE("deleteInfoByIds", r.apiInfo.DeleteInfoByIds) // 批量删除公告
|
||||
group.PUT("updateInfo", r.apiInfo.UpdateInfo) // 更新公告
|
||||
}
|
||||
{
|
||||
group := private.Group("info")
|
||||
group.GET("findInfo", r.apiInfo.FindInfo) // 根据ID获取公告
|
||||
group.GET("getInfoList", r.apiInfo.GetInfoList) // 获取公告列表
|
||||
}
|
||||
{
|
||||
group := public.Group("info")
|
||||
group.GET("getInfoDataSource", r.apiInfo.GetInfoDataSource) // 获取公告数据源
|
||||
group.GET("getInfoPublic", r.apiInfo.GetInfoPublic) // 获取公告列表
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package service
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
var Service *service
|
||||
|
||||
type service struct {
|
||||
Info *Info
|
||||
}
|
||||
|
||||
// NewService 创建服务实例
|
||||
func NewService(db *gorm.DB) *service {
|
||||
s := &service{
|
||||
Info: NewInfoService(db),
|
||||
}
|
||||
Service = s
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/announcement/model"
|
||||
"kra/internal/plugin/announcement/model/request"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Info 公告服务
|
||||
type Info struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewInfoService 创建公告服务
|
||||
func NewInfoService(db *gorm.DB) *Info {
|
||||
return &Info{db: db}
|
||||
}
|
||||
|
||||
// CreateInfo 创建公告记录
|
||||
func (s *Info) CreateInfo(info *model.Info) (err error) {
|
||||
err = s.db.Create(info).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteInfo 删除公告记录
|
||||
func (s *Info) DeleteInfo(ID string) (err error) {
|
||||
err = s.db.Delete(&model.Info{}, "id = ?", ID).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteInfoByIds 批量删除公告记录
|
||||
func (s *Info) DeleteInfoByIds(IDs []string) (err error) {
|
||||
err = s.db.Delete(&[]model.Info{}, "id in ?", IDs).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateInfo 更新公告记录
|
||||
func (s *Info) UpdateInfo(info model.Info) (err error) {
|
||||
err = s.db.Model(&model.Info{}).Where("id = ?", info.ID).Updates(&info).Error
|
||||
return err
|
||||
}
|
||||
|
||||
// GetInfo 根据ID获取公告记录
|
||||
func (s *Info) GetInfo(ID string) (info model.Info, err error) {
|
||||
err = s.db.Where("id = ?", ID).First(&info).Error
|
||||
return
|
||||
}
|
||||
|
||||
// GetInfoInfoList 分页获取公告记录
|
||||
func (s *Info) GetInfoInfoList(info request.InfoSearch) (list []model.Info, total int64, err error) {
|
||||
limit := info.PageSize
|
||||
offset := info.PageSize * (info.Page - 1)
|
||||
// 创建db
|
||||
db := s.db.Model(&model.Info{})
|
||||
var infos []model.Info
|
||||
// 如果有条件搜索 下方会自动创建搜索语句
|
||||
if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
|
||||
db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
|
||||
}
|
||||
err = db.Count(&total).Error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if limit != 0 {
|
||||
db = db.Limit(limit).Offset(offset)
|
||||
}
|
||||
err = db.Find(&infos).Error
|
||||
return infos, total, err
|
||||
}
|
||||
|
||||
// GetInfoDataSource 获取公告数据源
|
||||
func (s *Info) GetInfoDataSource() (res map[string][]map[string]any, err error) {
|
||||
res = make(map[string][]map[string]any)
|
||||
|
||||
userID := make([]map[string]any, 0)
|
||||
s.db.Table("sys_users").Select("nick_name as label,id as value").Scan(&userID)
|
||||
res["userID"] = userID
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package api
|
||||
|
||||
type ApiGroup struct {
|
||||
EmailApi
|
||||
}
|
||||
|
||||
var ApiGroupApp = new(ApiGroup)
|
||||
@@ -0,0 +1,50 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/email/model/response"
|
||||
"kra/internal/plugin/email/service"
|
||||
pkgResponse "kra/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type EmailApi struct{}
|
||||
|
||||
// EmailTest
|
||||
// @Tags System
|
||||
// @Summary 发送测试邮件
|
||||
// @Security ApiKeyAuth
|
||||
// @Produce application/json
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
|
||||
// @Router /email/emailTest [post]
|
||||
func (s *EmailApi) EmailTest(c *gin.Context) {
|
||||
err := service.ServiceGroupApp.EmailTest()
|
||||
if err != nil {
|
||||
pkgResponse.FailWithMessage("发送失败", c)
|
||||
return
|
||||
}
|
||||
pkgResponse.OkWithMessage("发送成功", c)
|
||||
}
|
||||
|
||||
// SendEmail
|
||||
// @Tags System
|
||||
// @Summary 发送邮件
|
||||
// @Security ApiKeyAuth
|
||||
// @Produce application/json
|
||||
// @Param data body response.Email true "发送邮件必须的参数"
|
||||
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
|
||||
// @Router /email/sendEmail [post]
|
||||
func (s *EmailApi) SendEmail(c *gin.Context) {
|
||||
var email response.Email
|
||||
err := c.ShouldBindJSON(&email)
|
||||
if err != nil {
|
||||
pkgResponse.FailWithMessage(err.Error(), c)
|
||||
return
|
||||
}
|
||||
err = service.ServiceGroupApp.SendEmail(email.To, email.Subject, email.Body)
|
||||
if err != nil {
|
||||
pkgResponse.FailWithMessage("发送失败", c)
|
||||
return
|
||||
}
|
||||
pkgResponse.OkWithMessage("发送成功", c)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
// Email 邮件配置
|
||||
type Email struct {
|
||||
To string `mapstructure:"to" json:"to" yaml:"to"` // 收件人:多个以英文逗号分隔 例:a@qq.com b@qq.com 正式开发中请把此项目作为参数使用
|
||||
From string `mapstructure:"from" json:"from" yaml:"from"` // 发件人 你自己要发邮件的邮箱
|
||||
Host string `mapstructure:"host" json:"host" yaml:"host"` // 服务器地址 例如 smtp.qq.com 请前往QQ或者你要发邮件的邮箱查看其smtp协议
|
||||
Secret string `mapstructure:"secret" json:"secret" yaml:"secret"` // 密钥 用于登录的密钥 最好不要用邮箱密码 去邮箱smtp申请一个用于登录的密钥
|
||||
Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称 发件人昵称 通常为自己的邮箱
|
||||
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口 请前往QQ或者你要发邮件的邮箱查看其smtp协议 大多为 465
|
||||
IsSSL bool `mapstructure:"is-ssl" json:"isSSL" yaml:"is-ssl"` // 是否SSL 是否开启SSL
|
||||
IsLoginAuth bool `mapstructure:"is-loginauth" json:"is-loginauth" yaml:"is-loginauth"` // 是否LoginAuth 是否使用LoginAuth认证
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package global
|
||||
|
||||
import "kra/internal/plugin/email/config"
|
||||
|
||||
var GlobalConfig = new(config.Email)
|
||||
@@ -0,0 +1,31 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/email/global"
|
||||
"kra/internal/plugin/email/router"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type emailPlugin struct{}
|
||||
|
||||
// CreateEmailPlug 创建邮件插件
|
||||
func CreateEmailPlug(To, From, Host, Secret, Nickname string, Port int, IsSSL bool, IsLoginAuth bool) *emailPlugin {
|
||||
global.GlobalConfig.To = To
|
||||
global.GlobalConfig.From = From
|
||||
global.GlobalConfig.Host = Host
|
||||
global.GlobalConfig.Secret = Secret
|
||||
global.GlobalConfig.Nickname = Nickname
|
||||
global.GlobalConfig.Port = Port
|
||||
global.GlobalConfig.IsSSL = IsSSL
|
||||
global.GlobalConfig.IsLoginAuth = IsLoginAuth
|
||||
return &emailPlugin{}
|
||||
}
|
||||
|
||||
func (*emailPlugin) Register(group *gin.RouterGroup) {
|
||||
router.RouterGroupApp.InitEmailRouter(group)
|
||||
}
|
||||
|
||||
func (*emailPlugin) RouterPath() string {
|
||||
return "email"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package response
|
||||
|
||||
// Email 邮件请求结构
|
||||
type Email struct {
|
||||
To string `json:"to"` // 邮件发送给谁
|
||||
Subject string `json:"subject"` // 邮件标题
|
||||
Body string `json:"body"` // 邮件内容
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package router
|
||||
|
||||
type RouterGroup struct {
|
||||
EmailRouter
|
||||
}
|
||||
|
||||
var RouterGroupApp = new(RouterGroup)
|
||||
@@ -0,0 +1,20 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/email/api"
|
||||
"kra/internal/server/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type EmailRouter struct{}
|
||||
|
||||
func (s *EmailRouter) InitEmailRouter(Router *gin.RouterGroup) {
|
||||
emailRouter := Router.Use(middleware.OperationRecord())
|
||||
EmailApi := api.ApiGroupApp.EmailApi.EmailTest
|
||||
SendEmail := api.ApiGroupApp.EmailApi.SendEmail
|
||||
{
|
||||
emailRouter.POST("emailTest", EmailApi) // 发送测试邮件
|
||||
emailRouter.POST("sendEmail", SendEmail) // 发送邮件
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package service
|
||||
|
||||
type ServiceGroup struct {
|
||||
EmailService
|
||||
}
|
||||
|
||||
var ServiceGroupApp = new(ServiceGroup)
|
||||
@@ -0,0 +1,24 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"kra/internal/plugin/email/utils"
|
||||
)
|
||||
|
||||
type EmailService struct{}
|
||||
|
||||
// EmailTest 发送邮件测试
|
||||
func (e *EmailService) EmailTest() (err error) {
|
||||
subject := "test"
|
||||
body := "test"
|
||||
err = utils.EmailTest(subject, body)
|
||||
return err
|
||||
}
|
||||
|
||||
// SendEmail 发送邮件
|
||||
// @params to string 收件人
|
||||
// @params subject string 标题(主题)
|
||||
// @params body string 邮件内容
|
||||
func (e *EmailService) SendEmail(to, subject, body string) (err error) {
|
||||
err = utils.Email(to, subject, body)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
|
||||
"github.com/jordan-wright/email"
|
||||
"kra/internal/plugin/email/global"
|
||||
)
|
||||
|
||||
// Email 发送邮件
|
||||
func Email(To, subject string, body string) error {
|
||||
to := strings.Split(To, ",")
|
||||
return send(to, subject, body)
|
||||
}
|
||||
|
||||
// ErrorToEmail 给email中间件错误发送邮件到指定邮箱
|
||||
func ErrorToEmail(subject string, body string) error {
|
||||
to := strings.Split(global.GlobalConfig.To, ",")
|
||||
if to[len(to)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除
|
||||
to = to[:len(to)-1]
|
||||
}
|
||||
return send(to, subject, body)
|
||||
}
|
||||
|
||||
// EmailTest Email测试方法
|
||||
func EmailTest(subject string, body string) error {
|
||||
to := []string{global.GlobalConfig.To}
|
||||
return send(to, subject, body)
|
||||
}
|
||||
|
||||
// send Email发送方法
|
||||
func send(to []string, subject string, body string) error {
|
||||
from := global.GlobalConfig.From
|
||||
nickname := global.GlobalConfig.Nickname
|
||||
secret := global.GlobalConfig.Secret
|
||||
host := global.GlobalConfig.Host
|
||||
port := global.GlobalConfig.Port
|
||||
isSSL := global.GlobalConfig.IsSSL
|
||||
isLoginAuth := global.GlobalConfig.IsLoginAuth
|
||||
|
||||
var auth smtp.Auth
|
||||
if isLoginAuth {
|
||||
auth = LoginAuth(from, secret)
|
||||
} else {
|
||||
auth = smtp.PlainAuth("", from, secret, host)
|
||||
}
|
||||
e := email.NewEmail()
|
||||
if nickname != "" {
|
||||
e.From = fmt.Sprintf("%s <%s>", nickname, from)
|
||||
} else {
|
||||
e.From = from
|
||||
}
|
||||
e.To = to
|
||||
e.Subject = subject
|
||||
e.HTML = []byte(body)
|
||||
var err error
|
||||
hostAddr := fmt.Sprintf("%s:%d", host, port)
|
||||
if isSSL {
|
||||
err = e.SendWithTLS(hostAddr, auth, &tls.Config{ServerName: host})
|
||||
} else {
|
||||
err = e.Send(hostAddr, auth)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// loginAuth 用于IBM、微软邮箱服务器的LOGIN认证方式
|
||||
type loginAuth struct {
|
||||
username, password string
|
||||
}
|
||||
|
||||
// LoginAuth 创建LOGIN认证
|
||||
func LoginAuth(username, password string) smtp.Auth {
|
||||
return &loginAuth{username, password}
|
||||
}
|
||||
|
||||
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||
return "LOGIN", []byte{}, nil
|
||||
}
|
||||
|
||||
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||
if more {
|
||||
switch string(fromServer) {
|
||||
case "Username:":
|
||||
return []byte(a.username), nil
|
||||
case "Password:":
|
||||
return []byte(a.password), nil
|
||||
default:
|
||||
// 邮箱服务器可能发送的其他提示信息
|
||||
prompt := strings.ToLower(string(fromServer))
|
||||
if strings.Contains(prompt, "username") || strings.Contains(prompt, "user") {
|
||||
return []byte(a.username), nil
|
||||
}
|
||||
if strings.Contains(prompt, "password") || strings.Contains(prompt, "pass") {
|
||||
return []byte(a.password), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"kra/internal/data/model"
|
||||
)
|
||||
|
||||
// RegisterApis 注册API到数据库
|
||||
func RegisterApis(db *gorm.DB, apis ...model.SysAPI) {
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
for _, api := range apis {
|
||||
err := tx.Model(model.SysAPI{}).Where("path = ? AND method = ? AND api_group = ? ", api.Path, api.Method, api.APIGroup).FirstOrCreate(&api).Error
|
||||
if err != nil {
|
||||
zap.L().Error("注册API失败", zap.Error(err), zap.String("api", api.Path), zap.String("method", api.Method), zap.String("apiGroup", api.APIGroup))
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
zap.L().Error("注册API失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterMenus 注册菜单到数据库
|
||||
func RegisterMenus(db *gorm.DB, menus ...model.SysBaseMenu) {
|
||||
if len(menus) == 0 {
|
||||
return
|
||||
}
|
||||
parentMenu := menus[0]
|
||||
otherMenus := menus[1:]
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
err := tx.Model(model.SysBaseMenu{}).Where("name = ? ", parentMenu.Name).FirstOrCreate(&parentMenu).Error
|
||||
if err != nil {
|
||||
zap.L().Error("注册菜单失败", zap.Error(err))
|
||||
return errors.Wrap(err, "注册菜单失败")
|
||||
}
|
||||
pid := parentMenu.ID
|
||||
for i := range otherMenus {
|
||||
otherMenus[i].ParentID = pid
|
||||
err = tx.Model(model.SysBaseMenu{}).Where("name = ? ", otherMenus[i].Name).FirstOrCreate(&otherMenus[i]).Error
|
||||
if err != nil {
|
||||
zap.L().Error("注册菜单失败", zap.Error(err))
|
||||
return errors.Wrap(err, "注册菜单失败")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
zap.L().Error("注册菜单失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user