Refactor import paths to use internal/pkg/httpx/params

- Updated multiple repository and service files to replace imports from "github.com/mlogclub/simple/web/params" with "cs-agent/internal/pkg/httpx/params".
- Adjusted context handling in auth_service and ws_service to use gin.Context instead of iris.Context.
- Ensured consistent usage of HTTP status responses across websocket handlers.
This commit is contained in:
mlogclub
2026-05-23 22:10:20 +08:00
parent f8b1ed42fa
commit 79614b2d07
140 changed files with 1117 additions and 595 deletions
+114 -94
View File
@@ -3,6 +3,8 @@ package bootstrap
import (
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"time"
@@ -13,131 +15,149 @@ import (
"cs-agent/internal/controllers/third"
"cs-agent/internal/middleware"
"cs-agent/internal/pkg/config"
"cs-agent/internal/pkg/ginx"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/cors"
"github.com/kataras/iris/v12/middleware/recover"
"github.com/kataras/iris/v12/mvc"
"github.com/gin-gonic/gin"
_ "cs-agent/internal/services/wx_callback_handlers"
)
func NewServer() (*iris.Application, error) {
func NewServer() (*gin.Engine, error) {
cfg := config.Current()
app := iris.New()
corsHandler := cors.New().
AllowOrigin("*").
AllowHeaders("Origin", "Content-Type", "Accept", "Authorization", "X-Requested-With", "X-Guest-Id", "X-Channel-Id", "X-External-Id", "X-External-Name", "X-Customer-Session-Token", "X-Customer-Session-Expires-At").
MaxAge(600).
ExposeHeaders("Content-Length", "Content-Type", "Authorization", "X-Guest-Id", "X-Channel-Id", "X-External-Id", "X-External-Name", "X-Customer-Session-Token", "X-Customer-Session-Expires-At").
Handler()
app.UseRouter(func(ctx iris.Context) {
// WebSocket upgrade is validated by the upgrader's origin policy.
app := gin.New()
app.Use(corsMiddleware())
app.Use(gin.Recovery())
app.Use(requestLogMiddleware())
app.Use(maxBodySizeMiddleware(cfg.Storage.MaxRequestBodySizeBytes()))
addRouter(app)
app.StaticFS(cfg.Storage.Local.BaseURL, http.Dir(cfg.Storage.Local.Root))
registerDashboardStatic(app, "web/out")
return app, nil
}
func corsMiddleware() gin.HandlerFunc {
allowHeaders := "Origin, Content-Type, Accept, Authorization, X-Requested-With, X-Guest-Id, X-Channel-Id, X-External-Id, X-External-Name, X-Customer-Session-Token, X-Customer-Session-Expires-At"
exposeHeaders := "Content-Length, Content-Type, Authorization, X-Guest-Id, X-Channel-Id, X-External-Id, X-External-Name, X-Customer-Session-Token, X-Customer-Session-Expires-At"
return func(ctx *gin.Context) {
if isWebsocketUpgrade(ctx) {
ctx.Next()
return
}
corsHandler(ctx)
})
app.UseRouter(recover.New())
app.UseRouter(func(ctx iris.Context) {
ctx.Header("Access-Control-Allow-Origin", "*")
ctx.Header("Access-Control-Allow-Headers", allowHeaders)
ctx.Header("Access-Control-Expose-Headers", exposeHeaders)
ctx.Header("Access-Control-Max-Age", "600")
if ctx.Request.Method == http.MethodOptions {
ctx.AbortWithStatus(http.StatusNoContent)
return
}
ctx.Next()
}
}
func requestLogMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
start := time.Now()
path := ctx.Path()
method := ctx.Method()
path := ctx.Request.URL.Path
method := ctx.Request.Method
ctx.Next()
slog.Info("http request",
"method", method,
"path", path,
"status", ctx.GetStatusCode(),
"status", ctx.Writer.Status(),
"elapsed", time.Since(start).Milliseconds(),
"clientIp", ctx.RemoteAddr(),
"clientIp", ctx.ClientIP(),
)
})
app.UseRouter(func(ctx iris.Context) {
ctx.SetMaxRequestBodySize(cfg.Storage.MaxRequestBodySizeBytes())
ctx.Next()
})
// 注册路由
addRouter(app)
// 注册本地存储静态资源服务
app.HandleDir(cfg.Storage.Local.BaseURL, iris.Dir(cfg.Storage.Local.Root), iris.DirOptions{
ShowList: false,
})
// 注册dashboard静态资源服务
app.HandleDir("/", iris.Dir("web/out"), iris.DirOptions{
IndexName: "index.html",
Compress: true,
ShowList: false,
})
return app, nil
}
}
func isWebsocketUpgrade(ctx iris.Context) bool {
func maxBodySizeMiddleware(limit int64) gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, limit)
ctx.Next()
}
}
func isWebsocketUpgrade(ctx *gin.Context) bool {
if !strings.EqualFold(ctx.GetHeader("Upgrade"), "websocket") {
return false
}
return strings.Contains(strings.ToLower(ctx.GetHeader("Connection")), "upgrade")
}
func addRouter(app *iris.Application) {
mcpHandler := mcps.NewHTTPHandler()
func addRouter(app *gin.Engine) {
app.Any("/api/mcp", gin.WrapH(mcps.NewHTTPHandler()))
app.Any("/api/mcp", iris.FromStd(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mcpHandler.ServeHTTP(w, r)
})))
apiGroup := app.Group("/api")
ginx.HandleController(apiGroup, "/auth", new(api.AuthController))
ginx.HandleController(apiGroup, "/channel", new(api.ChannelController))
ginx.HandleController(apiGroup, "/customer", new(api.CustomerController))
ginx.HandleController(apiGroup, "/conversation", new(api.ConversationController), middleware.ExternalUserMiddleware)
ginx.HandleController(apiGroup, "/message", new(api.MessageController), middleware.ExternalUserMiddleware)
mvc.Configure(app.Party("/api"), func(m *mvc.Application) {
m.Party("/auth").Handle(new(api.AuthController))
m.Party("/channel").Handle(new(api.ChannelController))
m.Party("/customer").Handle(new(api.CustomerController))
m.Party("/conversation", middleware.ExternalUserMiddleware).Handle(new(api.ConversationController))
m.Party("/message", middleware.ExternalUserMiddleware).Handle(new(api.MessageController))
})
wsGroup := app.Group("/api/ws")
wsGroup.GET("/dashboard", middleware.AuthMiddleware, services.WsService.HandleDashboardWS)
wsGroup.GET("/dashboard/notification", middleware.AuthMiddleware, services.WsService.HandleDashboardNotificationWS)
wsGroup.GET("/open", services.WsService.HandleOpenWS)
mvc.Configure(app.Party("/api/ws"), func(m *mvc.Application) {
m.Router.Get("/dashboard", middleware.AuthMiddleware, services.WsService.HandleDashboardWS)
m.Router.Get("/dashboard/notification", middleware.AuthMiddleware, services.WsService.HandleDashboardNotificationWS)
m.Router.Get("/open", services.WsService.HandleOpenWS)
})
dashboardGroup := app.Group("/api/dashboard", middleware.AuthMiddleware)
ginx.HandleController(dashboardGroup, "/dashboard", new(dashboard.DashboardController))
ginx.HandleController(dashboardGroup, "/user", new(dashboard.UserController))
ginx.HandleController(dashboardGroup, "/company", new(dashboard.CompanyController))
ginx.HandleController(dashboardGroup, "/customer", new(dashboard.CustomerController))
ginx.HandleController(dashboardGroup, "/customer-contact", new(dashboard.CustomerContactController))
ginx.HandleController(dashboardGroup, "/role", new(dashboard.RoleController))
ginx.HandleController(dashboardGroup, "/permission", new(dashboard.PermissionController))
ginx.HandleController(dashboardGroup, "/session", new(dashboard.SessionController))
ginx.HandleController(dashboardGroup, "/tag", new(dashboard.TagController))
ginx.HandleController(dashboardGroup, "/conversation", new(dashboard.ConversationController))
ginx.HandleController(dashboardGroup, "/ticket", new(dashboard.TicketController))
ginx.HandleController(dashboardGroup, "/notification", new(dashboard.NotificationController))
ginx.HandleController(dashboardGroup, "/quick-reply", new(dashboard.QuickReplyController))
ginx.HandleController(dashboardGroup, "/channel", new(dashboard.ChannelController))
ginx.HandleController(dashboardGroup, "/agent", new(dashboard.AgentController))
ginx.HandleController(dashboardGroup, "/agent-team", new(dashboard.AgentTeamController))
ginx.HandleController(dashboardGroup, "/agent-team-schedule", new(dashboard.AgentTeamScheduleController))
ginx.HandleController(dashboardGroup, "/ai-agent", new(dashboard.AIAgentController))
ginx.HandleController(dashboardGroup, "/ai-config", new(dashboard.AIConfigController))
ginx.HandleController(dashboardGroup, "/asset", new(dashboard.AssetController))
ginx.HandleController(dashboardGroup, "/knowledge-base", new(dashboard.KnowledgeBaseController))
ginx.HandleController(dashboardGroup, "/knowledge-document", new(dashboard.KnowledgeDocumentController))
ginx.HandleController(dashboardGroup, "/knowledge-faq", new(dashboard.KnowledgeFAQController))
ginx.HandleController(dashboardGroup, "/knowledge-retrieve", new(dashboard.KnowledgeRetrieveController))
ginx.HandleController(dashboardGroup, "/knowledge-retrieve-log", new(dashboard.KnowledgeRetrieveLogController))
ginx.HandleController(dashboardGroup, "/agent-run-log", new(dashboard.AgentRunLogController))
ginx.HandleController(dashboardGroup, "/skill-definition", new(dashboard.SkillDefinitionController))
ginx.HandleController(dashboardGroup, "/mcp", new(dashboard.MCPController))
mvc.Configure(app.Party("/api/dashboard", middleware.AuthMiddleware), func(m *mvc.Application) {
m.Party("/dashboard").Handle(new(dashboard.DashboardController))
m.Party("/user").Handle(new(dashboard.UserController))
m.Party("/company").Handle(new(dashboard.CompanyController))
m.Party("/customer").Handle(new(dashboard.CustomerController))
m.Party("/customer-contact").Handle(new(dashboard.CustomerContactController))
m.Party("/role").Handle(new(dashboard.RoleController))
m.Party("/permission").Handle(new(dashboard.PermissionController))
m.Party("/session").Handle(new(dashboard.SessionController))
m.Party("/tag").Handle(new(dashboard.TagController))
m.Party("/conversation").Handle(new(dashboard.ConversationController))
m.Party("/ticket").Handle(new(dashboard.TicketController))
m.Party("/notification").Handle(new(dashboard.NotificationController))
m.Party("/quick-reply").Handle(new(dashboard.QuickReplyController))
m.Party("/channel").Handle(new(dashboard.ChannelController))
m.Party("/agent").Handle(new(dashboard.AgentController))
m.Party("/agent-team").Handle(new(dashboard.AgentTeamController))
m.Party("/agent-team-schedule").Handle(new(dashboard.AgentTeamScheduleController))
m.Party("/ai-agent").Handle(new(dashboard.AIAgentController))
m.Party("/ai-config").Handle(new(dashboard.AIConfigController))
m.Party("/asset").Handle(new(dashboard.AssetController))
m.Party("/knowledge-base").Handle(new(dashboard.KnowledgeBaseController))
m.Party("/knowledge-document").Handle(new(dashboard.KnowledgeDocumentController))
m.Party("/knowledge-faq").Handle(new(dashboard.KnowledgeFAQController))
m.Party("/knowledge-retrieve").Handle(new(dashboard.KnowledgeRetrieveController))
m.Party("/knowledge-retrieve-log").Handle(new(dashboard.KnowledgeRetrieveLogController))
m.Party("/agent-run-log").Handle(new(dashboard.AgentRunLogController))
m.Party("/skill-definition").Handle(new(dashboard.SkillDefinitionController))
m.Party("/mcp").Handle(new(dashboard.MCPController))
})
thirdGroup := app.Group("/api/third")
ginx.HandleController(thirdGroup, "/wechat", new(third.WechatController))
}
mvc.Configure(app.Party("/api/third"), func(m *mvc.Application) {
m.Party("/wechat").Handle(new(third.WechatController))
func registerDashboardStatic(app *gin.Engine, root string) {
app.NoRoute(func(ctx *gin.Context) {
if strings.HasPrefix(ctx.Request.URL.Path, "/api/") {
ctx.JSON(http.StatusNotFound, gin.H{"success": false, "message": "not found"})
return
}
requestPath := filepath.Clean(strings.TrimPrefix(ctx.Request.URL.Path, "/"))
if strings.HasPrefix(requestPath, "..") {
ctx.Status(http.StatusBadRequest)
return
}
if requestPath == "." {
requestPath = "index.html"
}
fullPath := filepath.Join(root, requestPath)
if stat, err := os.Stat(fullPath); err == nil && !stat.IsDir() {
ctx.File(fullPath)
return
}
ctx.File(filepath.Join(root, "index.html"))
})
}
+45
View File
@@ -0,0 +1,45 @@
package bootstrap
import (
"net/http"
"testing"
"cs-agent/internal/pkg/config"
)
func TestNewServerRegistersGinRoutes(t *testing.T) {
config.SetCurrent(&config.Config{
Storage: config.StorageConfig{
Local: config.LocalStorageConfig{
Root: "storage",
BaseURL: "/storage",
},
},
})
app, err := NewServer()
if err != nil {
t.Fatalf("NewServer() error = %v", err)
}
routes := make(map[string]bool)
for _, route := range app.Routes() {
routes[route.Method+" "+route.Path] = true
}
expected := []string{
http.MethodPost + " /api/auth/login",
http.MethodGet + " /api/auth/profile",
http.MethodGet + " /api/dashboard/user/list",
http.MethodGet + " /api/dashboard/user/:id",
http.MethodPost + " /api/dashboard/user/create",
http.MethodPost + " /api/dashboard/conversation/send_message",
http.MethodGet + " /api/ws/dashboard",
http.MethodGet + " /api/ws/open",
}
for _, route := range expected {
if !routes[route] {
t.Fatalf("expected route %s to be registered", route)
}
}
}
+14 -13
View File
@@ -3,17 +3,18 @@ package api
import (
"cs-agent/internal/pkg/config"
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/pkg/httpx/params"
"cs-agent/internal/services"
"net/http"
"net/url"
"strings"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AuthController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AuthController) PostLogin() *web.JsonResult {
@@ -23,7 +24,7 @@ func (c *AuthController) PostLogin() *web.JsonResult {
return web.JsonError(err)
}
ret, err := services.AuthService.Login(req, cfg.Auth, c.Ctx.RemoteAddr(), c.Ctx.GetHeader("User-Agent"))
ret, err := services.AuthService.Login(req, cfg.Auth, c.Ctx.ClientIP(), c.Ctx.GetHeader("User-Agent"))
if err != nil {
return web.JsonError(err)
}
@@ -31,37 +32,37 @@ func (c *AuthController) PostLogin() *web.JsonResult {
}
func (c *AuthController) GetWxwork_login() {
loginURL, err := services.WxWorkLoginService.BuildWxWorkLoginURL(c.Ctx.URLParam("next"))
loginURL, err := services.WxWorkLoginService.BuildWxWorkLoginURL(c.Ctx.Query("next"))
if err != nil {
c.redirectWxWorkError(err.Error())
return
}
c.Ctx.Redirect(loginURL, iris.StatusFound)
c.Ctx.Redirect(http.StatusFound, loginURL)
}
func (c *AuthController) GetWxwork_qr_login() {
loginURL, err := services.WxWorkLoginService.BuildWxWorkQRCodeLoginURL(c.Ctx.URLParam("next"))
loginURL, err := services.WxWorkLoginService.BuildWxWorkQRCodeLoginURL(c.Ctx.Query("next"))
if err != nil {
c.redirectWxWorkError(err.Error())
return
}
c.Ctx.Redirect(loginURL, iris.StatusFound)
c.Ctx.Redirect(http.StatusFound, loginURL)
}
func (c *AuthController) GetWxwork_callback() {
cfg := config.Current()
ticket, next, err := services.WxWorkLoginService.LoginByWxWork(
c.Ctx.URLParam("code"),
c.Ctx.URLParam("state"),
c.Ctx.Query("code"),
c.Ctx.Query("state"),
cfg.Auth,
c.Ctx.RemoteAddr(),
c.Ctx.ClientIP(),
c.Ctx.GetHeader("User-Agent"),
)
if err != nil {
c.redirectWxWorkError(err.Error())
return
}
c.Ctx.Redirect("/dashboard/login/wxwork/callback?ticket="+url.QueryEscape(ticket)+"&next="+url.QueryEscape(next), iris.StatusFound)
c.Ctx.Redirect(http.StatusFound, "/dashboard/login/wxwork/callback?ticket="+url.QueryEscape(ticket)+"&next="+url.QueryEscape(next))
}
func (c *AuthController) PostWxwork_exchange() *web.JsonResult {
@@ -95,5 +96,5 @@ func (c *AuthController) redirectWxWorkError(message string) {
if idx := strings.Index(message, ": "); idx >= 0 {
message = message[idx+2:]
}
c.Ctx.Redirect("/login?wxworkError="+url.QueryEscape(message), iris.StatusFound)
c.Ctx.Redirect(http.StatusFound, "/login?wxworkError="+url.QueryEscape(message))
}
@@ -6,12 +6,12 @@ import (
"cs-agent/internal/pkg/errorsx"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
)
type ChannelController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *ChannelController) AnyConfig() *web.JsonResult {
@@ -4,23 +4,23 @@ import (
"cs-agent/internal/builders"
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/pkg/irisx"
"cs-agent/internal/pkg/httpx"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type ConversationController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *ConversationController) GetBy(id int64) *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -45,7 +45,7 @@ func (c *ConversationController) PostCreate_or_match() *web.JsonResult {
if channel == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -61,7 +61,7 @@ func (c *ConversationController) PostClose() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -4,12 +4,12 @@ import (
"cs-agent/internal/pkg/openidentity"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
)
type CustomerController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *CustomerController) PostSession_exchange() *web.JsonResult {
+13 -17
View File
@@ -4,26 +4,26 @@ import (
"cs-agent/internal/builders"
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/pkg/enums"
"cs-agent/internal/pkg/irisx"
"cs-agent/internal/pkg/httpx"
"cs-agent/internal/services"
"strconv"
"strings"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
"github.com/spf13/cast"
)
type MessageController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *MessageController) AnyList() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -57,7 +57,7 @@ func (c *MessageController) PostSend() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -78,7 +78,7 @@ func (c *MessageController) PostRead() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
@@ -97,12 +97,12 @@ func (c *MessageController) PostUpload_image() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
rawConv := strings.TrimSpace(c.Ctx.FormValue("conversationId"))
rawConv := strings.TrimSpace(params.FormValue(c.Ctx, "conversationId"))
if rawConv == "" {
return web.JsonErrorMsg("conversationId不能为空")
}
@@ -121,12 +121,10 @@ func (c *MessageController) PostUpload_image() *web.JsonResult {
return web.JsonError(err)
}
f, header, err := c.Ctx.FormFile("file")
header, err := c.Ctx.FormFile("file")
if err != nil {
return web.JsonErrorMsg("请选择上传图片")
}
_ = f.Close()
if !strings.HasPrefix(strings.ToLower(header.Header.Get("Content-Type")), "image/") {
return web.JsonErrorMsg("仅支持上传图片文件")
}
@@ -142,12 +140,12 @@ func (c *MessageController) PostUpload_attachment() *web.JsonResult {
if services.ChannelService.GetEnabledChannel(c.Ctx) == nil {
return web.JsonErrorMsg("接入渠道未初始化")
}
external := irisx.GetExternalUser(c.Ctx)
external := httpx.GetExternalUser(c.Ctx)
if external == nil {
return web.JsonErrorMsg("外部身份未初始化")
}
rawConv := strings.TrimSpace(c.Ctx.FormValue("conversationId"))
rawConv := strings.TrimSpace(params.FormValue(c.Ctx, "conversationId"))
if rawConv == "" {
return web.JsonErrorMsg("conversationId不能为空")
}
@@ -159,12 +157,10 @@ func (c *MessageController) PostUpload_attachment() *web.JsonResult {
return web.JsonError(err)
}
f, header, err := c.Ctx.FormFile("file")
header, err := c.Ctx.FormFile("file")
if err != nil {
return web.JsonErrorMsg("请选择上传附件")
}
_ = f.Close()
item, err := services.AssetService.UploadFile(header, "attachments", nil)
if err != nil {
return web.JsonError(err)
@@ -6,13 +6,13 @@ import (
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AgentController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AgentController) AnyList() *web.JsonResult {
@@ -6,13 +6,13 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AgentRunLogController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AgentRunLogController) AnyList() *web.JsonResult {
@@ -8,14 +8,14 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AgentTeamController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AgentTeamController) AnyList() *web.JsonResult {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AgentTeamScheduleController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AgentTeamScheduleController) AnyList() *web.JsonResult {
@@ -13,14 +13,14 @@ import (
"cs-agent/internal/pkg/utils"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AIAgentController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AIAgentController) AnyList() *web.JsonResult {
@@ -114,7 +114,7 @@ func (c *AIAgentController) PostUpdate_sort() *web.JsonResult {
return web.JsonError(err)
}
var ids []int64
if err := c.Ctx.ReadJSON(&ids); err != nil {
if err := params.ReadJSON(c.Ctx, &ids); err != nil {
return web.JsonError(err)
}
if err := services.AIAgentService.UpdateSort(ids); err != nil {
@@ -7,13 +7,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AIConfigController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AIConfigController) AnyList() *web.JsonResult {
@@ -133,7 +133,7 @@ func (c *AIConfigController) PostUpdate_sort() *web.JsonResult {
}
var ids []int64
if err := c.Ctx.ReadJSON(&ids); err != nil {
if err := params.ReadJSON(c.Ctx, &ids); err != nil {
return web.JsonError(err)
}
if err := services.AIConfigService.UpdateSort(ids); err != nil {
@@ -9,13 +9,13 @@ import (
"cs-agent/internal/services"
"strings"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type AssetController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *AssetController) AnyList() *web.JsonResult {
@@ -29,7 +29,7 @@ func (c *AssetController) AnyList() *web.JsonResult {
params.QueryFilter{ParamName: "createUserId"},
params.QueryFilter{ParamName: "filename", Op: params.Like},
).Desc("id")
if strings.TrimSpace(c.Ctx.URLParam("status")) == "" {
if strings.TrimSpace(c.Ctx.Query("status")) == "" {
cnd = cnd.Eq("status", enums.AssetStatusSuccess)
}
@@ -62,12 +62,10 @@ func (c *AssetController) PostCreate() *web.JsonResult {
if err := params.ReadForm(c.Ctx, &req); err != nil {
return web.JsonError(err)
}
f, header, err := c.Ctx.FormFile("file")
header, err := c.Ctx.FormFile("file")
if err != nil {
return web.JsonErrorMsg("请选择上传文件")
}
_ = f.Close()
item, err := services.AssetService.UploadFile(header, req.Prefix, operator)
if err != nil {
return web.JsonError(err)
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type ChannelController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *ChannelController) AnyList() *web.JsonResult {
@@ -7,13 +7,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type CompanyController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *CompanyController) AnyList() *web.JsonResult {
@@ -10,15 +10,15 @@ import (
"strconv"
"strings"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
"github.com/spf13/cast"
)
type ConversationController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *ConversationController) AnyList() *web.JsonResult {
@@ -272,7 +272,7 @@ func (c *ConversationController) PostUpload_image() *web.JsonResult {
return web.JsonError(err)
}
rawConv := strings.TrimSpace(c.Ctx.FormValue("conversationId"))
rawConv := strings.TrimSpace(params.FormValue(c.Ctx, "conversationId"))
if rawConv == "" {
return web.JsonErrorMsg("conversationId不能为空")
}
@@ -284,12 +284,10 @@ func (c *ConversationController) PostUpload_image() *web.JsonResult {
return web.JsonError(err)
}
f, header, err := c.Ctx.FormFile("file")
header, err := c.Ctx.FormFile("file")
if err != nil {
return web.JsonErrorMsg("请选择上传图片")
}
_ = f.Close()
if !strings.HasPrefix(strings.ToLower(header.Header.Get("Content-Type")), "image/") {
return web.JsonErrorMsg("仅支持上传图片文件")
}
@@ -307,7 +305,7 @@ func (c *ConversationController) PostUpload_attachment() *web.JsonResult {
return web.JsonError(err)
}
rawConv := strings.TrimSpace(c.Ctx.FormValue("conversationId"))
rawConv := strings.TrimSpace(params.FormValue(c.Ctx, "conversationId"))
if rawConv == "" {
return web.JsonErrorMsg("conversationId不能为空")
}
@@ -319,12 +317,10 @@ func (c *ConversationController) PostUpload_attachment() *web.JsonResult {
return web.JsonError(err)
}
f, header, err := c.Ctx.FormFile("file")
header, err := c.Ctx.FormFile("file")
if err != nil {
return web.JsonErrorMsg("请选择上传附件")
}
_ = f.Close()
item, err := services.AssetService.UploadFile(header, "attachments", operator)
if err != nil {
return web.JsonError(err)
@@ -6,13 +6,13 @@ import (
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type CustomerContactController struct {
Ctx iris.Context
Ctx *gin.Context
}
// AnyList GET/POST /customer-contact/list?customerId=
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type CustomerController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *CustomerController) PostList() *web.JsonResult {
@@ -3,13 +3,13 @@ package dashboard
import (
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type DashboardController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *DashboardController) GetOverview() *web.JsonResult {
@@ -12,14 +12,14 @@ import (
"cs-agent/internal/repositories"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type KnowledgeBaseController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *KnowledgeBaseController) AnyList() *web.JsonResult {
@@ -127,7 +127,7 @@ func (c *KnowledgeBaseController) PostDelete() *web.JsonResult {
func (c *KnowledgeBaseController) PostUpdate_sort() *web.JsonResult {
var ids []int64
if err := c.Ctx.ReadJSON(&ids); err != nil {
if err := params.ReadJSON(c.Ctx, &ids); err != nil {
return web.JsonError(err)
}
if err := services.KnowledgeBaseService.UpdateSort(ids); err != nil {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type KnowledgeDocumentController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *KnowledgeDocumentController) AnyList() *web.JsonResult {
@@ -7,13 +7,13 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type KnowledgeFAQController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *KnowledgeFAQController) AnyList() *web.JsonResult {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type KnowledgeRetrieveController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *KnowledgeRetrieveController) PostDebugSearch() *web.JsonResult {
@@ -6,13 +6,13 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type KnowledgeRetrieveLogController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *KnowledgeRetrieveLogController) AnyList() *web.JsonResult {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type MCPController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *MCPController) AnyList_servers() *web.JsonResult {
@@ -10,13 +10,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type NotificationController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *NotificationController) AnyList() *web.JsonResult {
@@ -31,7 +31,7 @@ func (c *NotificationController) AnyList() *web.JsonResult {
Eq("status", enums.StatusOk).
Desc("id")
switch strings.TrimSpace(c.Ctx.URLParam("readStatus")) {
switch strings.TrimSpace(c.Ctx.Query("readStatus")) {
case "unread":
cnd.Where("read_at IS NULL")
case "read":
@@ -5,14 +5,14 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type PermissionController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *PermissionController) AnyList() *web.JsonResult {
@@ -7,14 +7,14 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type QuickReplyController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *QuickReplyController) AnyList() *web.JsonResult {
@@ -6,14 +6,14 @@ import (
"cs-agent/internal/pkg/dto/response"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type RoleController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *RoleController) AnyList() *web.JsonResult {
@@ -177,7 +177,7 @@ func (c *RoleController) PostAssign_permission() *web.JsonResult {
func (c *RoleController) PostUpdate_sort() *web.JsonResult {
var ids []int64
if err := c.Ctx.ReadJSON(&ids); err != nil {
if err := params.ReadJSON(c.Ctx, &ids); err != nil {
return web.JsonError(err)
}
if err := services.RoleService.UpdateSort(ids); err != nil {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/services"
"time"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type SessionController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *SessionController) AnyList() *web.JsonResult {
@@ -12,13 +12,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type SkillDefinitionController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *SkillDefinitionController) AnyList() *web.JsonResult {
@@ -6,13 +6,13 @@ import (
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type TagController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *TagController) AnyList() *web.JsonResult {
@@ -101,7 +101,7 @@ func (c *TagController) PostDelete() *web.JsonResult {
func (c *TagController) PostUpdate_sort() *web.JsonResult {
var ids []int64
if err := c.Ctx.ReadJSON(&ids); err != nil {
if err := params.ReadJSON(c.Ctx, &ids); err != nil {
return web.JsonError(err)
}
if err := services.TagService.UpdateSort(ids); err != nil {
@@ -8,14 +8,14 @@ import (
"cs-agent/internal/pkg/dto/request"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type TicketController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *TicketController) AnyList() *web.JsonResult {
@@ -8,13 +8,13 @@ import (
"cs-agent/internal/pkg/enums"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
"github.com/mlogclub/simple/web/params"
)
type UserController struct {
Ctx iris.Context
Ctx *gin.Context
}
func (c *UserController) AnyList() *web.JsonResult {
+15 -13
View File
@@ -1,35 +1,37 @@
package third
import (
"cs-agent/internal/pkg/httpx/params"
"cs-agent/internal/wxwork"
"io"
"net/http"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/silenceper/wechat/v2/work/kf"
)
type WechatController struct {
Ctx iris.Context
Ctx *gin.Context
}
// GetCallback GET请求用于校验回调是否配置正确
func (c *WechatController) GetCallback() {
cli, err := wxwork.GetWorkCli().GetKF()
if err != nil {
c.Ctx.StopWithError(http.StatusInternalServerError, err)
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
options := kf.SignatureOptions{}
if err := c.Ctx.ReadForm(&options); err != nil {
c.Ctx.StopWithError(http.StatusUnauthorized, err)
if err := params.ReadForm(c.Ctx, &options); err != nil {
c.Ctx.AbortWithError(http.StatusUnauthorized, err)
return
}
// 调用VerifyURL方法校验当前请求,如果合法则把解密后的内容作为响应返回给微信服务器
echo, err := cli.VerifyURL(options)
if err == nil {
c.Ctx.WriteString(echo)
c.Ctx.String(http.StatusOK, echo)
} else {
c.Ctx.StopWithError(http.StatusUnauthorized, err)
c.Ctx.AbortWithError(http.StatusUnauthorized, err)
}
}
@@ -37,7 +39,7 @@ func (c *WechatController) GetCallback() {
func (c *WechatController) PostCallback() {
cli, err := wxwork.GetWorkCli().GetKF()
if err != nil {
c.Ctx.StopWithError(http.StatusInternalServerError, err)
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
var (
@@ -45,22 +47,22 @@ func (c *WechatController) PostCallback() {
body []byte
)
// 读取原始消息内容
body, err = c.Ctx.GetBody()
body, err = io.ReadAll(c.Ctx.Request.Body)
if err != nil {
c.Ctx.StopWithError(http.StatusInternalServerError, err)
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
// 解析原始数据
message, err = cli.GetCallbackMessage(body)
if err != nil {
c.Ctx.StopWithError(http.StatusInternalServerError, err)
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
if err := wxwork.ConsumeCallback(message); err != nil {
c.Ctx.StopWithError(http.StatusInternalServerError, err)
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Ctx.WriteString("ok")
c.Ctx.String(http.StatusOK, "ok")
}
+5 -5
View File
@@ -3,21 +3,21 @@ package middleware
import (
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
)
func AuthMiddleware(ctx iris.Context) {
func AuthMiddleware(ctx *gin.Context) {
if !authenticateRequest(ctx) {
return
}
ctx.Next()
}
func authenticateRequest(ctx iris.Context) bool {
func authenticateRequest(ctx *gin.Context) bool {
if _, err := services.AuthService.Authenticate(ctx); err != nil {
_ = ctx.JSON(web.JsonError(err))
ctx.StopExecution()
ctx.JSON(200, web.JsonError(err))
ctx.Abort()
return false
}
return true
+8 -8
View File
@@ -1,27 +1,27 @@
package middleware
import (
"cs-agent/internal/pkg/irisx"
"cs-agent/internal/pkg/httpx"
"cs-agent/internal/services"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
)
func ExternalUserMiddleware(ctx iris.Context) {
func ExternalUserMiddleware(ctx *gin.Context) {
channel := services.ChannelService.GetEnabledChannel(ctx)
if channel == nil {
ctx.StopExecution()
_ = ctx.JSON(web.JsonErrorMsg("接入渠道异常"))
ctx.JSON(200, web.JsonErrorMsg("接入渠道异常"))
ctx.Abort()
return
}
result, err := services.CustomerSessionService.VerifyRequest(ctx, channel)
if err != nil {
ctx.StopExecution()
_ = ctx.JSON(web.JsonError(err))
ctx.JSON(200, web.JsonError(err))
ctx.Abort()
return
}
services.CustomerSessionService.SetRefreshHeaders(ctx, result)
irisx.SetExternalUser(ctx, result.ExternalUser)
httpx.SetExternalUser(ctx, result.ExternalUser)
ctx.Next()
}
+137
View File
@@ -0,0 +1,137 @@
package ginx
import (
"net/http"
"reflect"
"strconv"
"strings"
"unicode"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/web"
)
var jsonResultType = reflect.TypeOf((*web.JsonResult)(nil))
func HandleController(group *gin.RouterGroup, relativePath string, prototype any, handlers ...gin.HandlerFunc) {
router := group.Group(relativePath, handlers...)
t := reflect.TypeOf(prototype)
if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
panic("ginx.HandleController requires a pointer to a controller struct")
}
for i := 0; i < t.NumMethod(); i++ {
method := t.Method(i)
httpMethods, path, ok := parseAction(method)
if !ok {
continue
}
handler := buildHandler(t, method)
for _, httpMethod := range httpMethods {
router.Handle(httpMethod, path, handler)
}
}
}
func parseAction(method reflect.Method) ([]string, string, bool) {
prefixes := []struct {
name string
methods []string
}{
{"Any", []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions}},
{"Get", []string{http.MethodGet}},
{"Post", []string{http.MethodPost}},
{"Put", []string{http.MethodPut}},
{"Delete", []string{http.MethodDelete}},
}
for _, prefix := range prefixes {
if !strings.HasPrefix(method.Name, prefix.name) {
continue
}
suffix := strings.TrimPrefix(method.Name, prefix.name)
return prefix.methods, actionPath(suffix, method.Type.NumIn()-1), true
}
return nil, "", false
}
func actionPath(suffix string, argCount int) string {
if suffix == "" {
return "/"
}
if suffix == "By" && argCount == 1 {
return "/:id"
}
if strings.HasSuffix(suffix, "By") && argCount == 1 {
base := strings.TrimSuffix(suffix, "By")
return "/" + actionSegmentPath(base) + "/:id"
}
return "/" + actionSegmentPath(suffix)
}
func actionSegmentPath(s string) string {
if s == "" {
return ""
}
parts := strings.Split(s, "_")
for i, part := range parts {
parts[i] = camelToPath(part)
}
return strings.Join(parts, "_")
}
func camelToPath(s string) string {
var b strings.Builder
for i, r := range s {
if unicode.IsUpper(r) {
if i > 0 {
b.WriteByte('/')
}
r = unicode.ToLower(r)
}
b.WriteRune(r)
}
return b.String()
}
func buildHandler(controllerType reflect.Type, method reflect.Method) gin.HandlerFunc {
return func(ctx *gin.Context) {
controller := reflect.New(controllerType.Elem())
if field := controller.Elem().FieldByName("Ctx"); field.IsValid() && field.CanSet() {
field.Set(reflect.ValueOf(ctx))
}
args := []reflect.Value{controller}
for i := 1; i < method.Type.NumIn(); i++ {
argType := method.Type.In(i)
raw := ctx.Param("id")
value, ok := convertPathArg(raw, argType)
if !ok {
ctx.JSON(http.StatusBadRequest, web.JsonErrorMsg("路径参数错误"))
return
}
args = append(args, value)
}
results := method.Func.Call(args)
if len(results) == 0 || results[0].IsNil() {
return
}
if result, ok := results[0].Interface().(*web.JsonResult); ok {
ctx.JSON(http.StatusOK, result)
}
}
}
func convertPathArg(raw string, t reflect.Type) (reflect.Value, bool) {
switch t.Kind() {
case reflect.Int64:
v, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return reflect.Value{}, false
}
return reflect.ValueOf(v), true
case reflect.String:
return reflect.ValueOf(raw), true
default:
return reflect.Zero(t), false
}
}
@@ -1,28 +1,28 @@
package irisx
package httpx
import (
"cs-agent/internal/pkg/httpx/params"
"cs-agent/internal/pkg/openidentity"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/web/params"
)
const (
ctxKeyExternalUser = "externalUser"
)
func SetExternalUser(ctx iris.Context, ext *openidentity.ExternalUser) {
ctx.Values().Set(ctxKeyExternalUser, ext)
func SetExternalUser(ctx *gin.Context, ext *openidentity.ExternalUser) {
ctx.Set(ctxKeyExternalUser, ext)
}
func GetExternalUser(ctx iris.Context) *openidentity.ExternalUser {
v := ctx.Values().Get(ctxKeyExternalUser)
func GetExternalUser(ctx *gin.Context) *openidentity.ExternalUser {
v, _ := ctx.Get(ctxKeyExternalUser)
ext, _ := v.(*openidentity.ExternalUser)
return ext
}
func GetChannelID(ctx iris.Context) string {
func GetChannelID(ctx *gin.Context) string {
if channelID := ctx.GetHeader("X-Channel-ID"); strs.IsNotBlank(channelID) {
return channelID
}
+270
View File
@@ -0,0 +1,270 @@
package params
import (
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/gorilla/schema"
"github.com/mlogclub/simple/common/dates"
"github.com/mlogclub/simple/common/jsons"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"github.com/spf13/cast"
)
var (
decoder = schema.NewDecoder()
validate = validator.New()
)
func init() {
decoder.SetAliasTag("form")
decoder.ZeroEmpty(true)
decoder.IgnoreUnknownKeys(true)
}
func paramError(name string) error {
return fmt.Errorf("unable to find param value '%s'", name)
}
func ReadForm(ctx *gin.Context, obj any) error {
if ctx == nil {
return errors.New("request context is nil")
}
if err := ctx.Request.ParseForm(); err != nil {
return err
}
values := ctx.Request.Form
if len(values) == 0 {
if err := ctx.Request.ParseMultipartForm(32 << 20); err != nil && !errors.Is(err, http.ErrNotMultipart) {
return err
}
values = ctx.Request.Form
}
if len(values) == 0 {
return nil
}
if err := decoder.Decode(obj, values); err != nil {
return err
}
return validate.Struct(obj)
}
func ReadJSON(ctx *gin.Context, obj any) error {
if ctx == nil {
return errors.New("request context is nil")
}
if err := ctx.ShouldBindJSON(obj); err != nil {
return err
}
return validate.Struct(obj)
}
func Get(ctx *gin.Context, name string) (string, bool) {
str := FormValue(ctx, name)
return str, str != ""
}
func GetInt64(ctx *gin.Context, name string) (int64, bool) {
str, ok := Get(ctx, name)
if !ok {
return 0, false
}
value, err := cast.ToInt64E(str)
if err != nil {
return 0, false
}
return value, true
}
func GetInt(ctx *gin.Context, name string) (int, bool) {
str, ok := Get(ctx, name)
if !ok {
return 0, false
}
value, err := cast.ToIntE(str)
if err != nil {
return 0, false
}
return value, true
}
func GetBool(ctx *gin.Context, name string) (bool, bool) {
str, ok := Get(ctx, name)
if !ok {
return false, false
}
value, err := cast.ToBoolE(str)
if err != nil {
return false, false
}
return value, true
}
func GetTime(ctx *gin.Context, name string) *time.Time {
value, _ := Get(ctx, name)
if strs.IsBlank(value) {
return nil
}
layouts := []string{dates.FmtDateTime, dates.FmtDate, dates.FmtDateTimeNoSeconds}
for _, layout := range layouts {
if ret, err := dates.Parse(value, layout); err == nil {
return &ret
}
}
return nil
}
func GetInt64Arr(ctx *gin.Context, name string) []int64 {
str, ok := Get(ctx, name)
if !ok {
return nil
}
str = strings.TrimSpace(str)
if strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]") {
var ret []int64
if err := jsons.Parse(str, &ret); err != nil {
slog.Error(err.Error())
}
return ret
}
return StrSplitToInt64Arr(str)
}
func StrSplitToInt64Arr(str string) (ret []int64) {
if strs.IsBlank(str) {
return ret
}
for _, s := range strings.Split(str, ",") {
i, err := cast.ToInt64E(strings.TrimSpace(s))
if err == nil {
ret = append(ret, i)
}
}
return ret
}
func FormValue(ctx *gin.Context, name string) string {
if ctx == nil {
return ""
}
if value := ctx.PostForm(name); value != "" {
return value
}
return ctx.Query(name)
}
func FormValueRequired(ctx *gin.Context, name string) (string, error) {
str := FormValue(ctx, name)
if len(str) == 0 {
return "", errors.New("参数:" + name + "不能为空")
}
return str, nil
}
func FormValueDefault(ctx *gin.Context, name, def string) string {
if value := FormValue(ctx, name); value != "" {
return value
}
return def
}
func FormValueInt(ctx *gin.Context, name string) (int, error) {
str := FormValue(ctx, name)
if str == "" {
return 0, paramError(name)
}
return strconv.Atoi(str)
}
func FormValueIntDefault(ctx *gin.Context, name string, def int) int {
if v, err := FormValueInt(ctx, name); err == nil {
return v
}
return def
}
func FormValueInt64(ctx *gin.Context, name string) (int64, error) {
str := FormValue(ctx, name)
if str == "" {
return 0, paramError(name)
}
return strconv.ParseInt(str, 10, 64)
}
func FormValueInt64Default(ctx *gin.Context, name string, def int64) int64 {
if v, err := FormValueInt64(ctx, name); err == nil {
return v
}
return def
}
func FormValueInt64Array(ctx *gin.Context, name string) []int64 {
str := strings.TrimSpace(FormValue(ctx, name))
if strings.HasPrefix(str, "[") && strings.HasSuffix(str, "]") {
var ret []int64
if err := jsons.Parse(str, &ret); err != nil {
slog.Error(err.Error())
}
return ret
}
return StrSplitToInt64Arr(str)
}
func FormValueStringArray(ctx *gin.Context, name string) []string {
str := FormValue(ctx, name)
if len(str) == 0 {
return nil
}
var ret []string
for _, s := range strings.Split(str, ",") {
s = strings.TrimSpace(s)
if len(s) > 0 {
ret = append(ret, s)
}
}
return ret
}
func FormValueBool(ctx *gin.Context, name string) (bool, error) {
str := FormValue(ctx, name)
if str == "" {
return false, paramError(name)
}
return strconv.ParseBool(str)
}
func FormValueBoolDefault(ctx *gin.Context, name string, def bool) bool {
str := FormValue(ctx, name)
if str == "" {
return def
}
value, err := strconv.ParseBool(str)
if err != nil {
return def
}
return value
}
func FormDate(ctx *gin.Context, name string) *time.Time {
return GetTime(ctx, name)
}
func GetPaging(ctx *gin.Context) *sqls.Paging {
page := FormValueIntDefault(ctx, "page", 1)
limit := FormValueIntDefault(ctx, "limit", 20)
if page <= 0 {
page = 1
}
if limit <= 0 {
limit = 20
}
return &sqls.Paging{Page: page, Limit: limit}
}
@@ -0,0 +1,79 @@
package params
import (
"strings"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/common/strs/strcase"
"github.com/mlogclub/simple/sqls"
)
type QueryOp string
const (
Eq QueryOp = "eq"
Gt QueryOp = "gt"
Lt QueryOp = "lt"
Gte QueryOp = "gte"
Lte QueryOp = "lte"
Like QueryOp = "like"
In QueryOp = "in"
Starting QueryOp = "starting"
Ending QueryOp = "ending"
)
type QueryFilter struct {
ParamName string
Op QueryOp
ColumnName string
ValueWrapper func(origin string) string
}
func NewPagedSqlCnd(ctx *gin.Context, filters ...QueryFilter) *sqls.Cnd {
cnd := NewSqlCnd(ctx, filters...)
p := GetPaging(ctx)
cnd.Page(p.Page, p.Limit)
return cnd
}
func NewSqlCnd(ctx *gin.Context, filters ...QueryFilter) *sqls.Cnd {
cnd := sqls.NewCnd()
for _, filter := range filters {
columnName := filter.ColumnName
paramValue := FormValue(ctx, filter.ParamName)
if strs.IsBlank(string(filter.Op)) {
filter.Op = Eq
}
if filter.ValueWrapper != nil {
paramValue = filter.ValueWrapper(paramValue)
}
if strs.IsBlank(paramValue) {
continue
}
if strs.IsBlank(columnName) {
columnName = strcase.ToSnake(filter.ParamName)
}
switch filter.Op {
case Eq:
cnd.Eq(columnName, paramValue)
case Gt:
cnd.Gt(columnName, paramValue)
case Lt:
cnd.Lt(columnName, paramValue)
case Gte:
cnd.Gte(columnName, paramValue)
case Lte:
cnd.Lte(columnName, paramValue)
case Like:
cnd.Like(columnName, paramValue)
case Starting:
cnd.Starting(columnName, paramValue)
case Ending:
cnd.Ending(columnName, paramValue)
case In:
cnd.In(columnName, strings.Split(paramValue, ","))
}
}
return cnd
}
+106
View File
@@ -0,0 +1,106 @@
package params
import (
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs/strcase"
"github.com/mlogclub/simple/sqls"
)
type QueryParams struct {
Ctx *gin.Context
sqls.Cnd
}
func NewQueryParams(ctx *gin.Context) *QueryParams {
return &QueryParams{Ctx: ctx}
}
func (q *QueryParams) getValueByColumn(column string) string {
if q.Ctx == nil {
return ""
}
return FormValue(q.Ctx, strcase.ToLowerCamel(column))
}
func (q *QueryParams) EqByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Eq(column, value)
}
return q
}
func (q *QueryParams) NotEqByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.NotEq(column, value)
}
return q
}
func (q *QueryParams) GtByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Gt(column, value)
}
return q
}
func (q *QueryParams) GteByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Gte(column, value)
}
return q
}
func (q *QueryParams) LtByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Lt(column, value)
}
return q
}
func (q *QueryParams) LteByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Lte(column, value)
}
return q
}
func (q *QueryParams) LikeByReq(column string) *QueryParams {
if value := q.getValueByColumn(column); len(value) > 0 {
q.Like(column, value)
}
return q
}
func (q *QueryParams) PageByReq() *QueryParams {
if q.Ctx == nil {
return q
}
paging := GetPaging(q.Ctx)
q.Page(paging.Page, paging.Limit)
return q
}
func (q *QueryParams) Asc(column string) *QueryParams {
q.Orders = append(q.Orders, sqls.OrderByCol{Column: column, Asc: true})
return q
}
func (q *QueryParams) Desc(column string) *QueryParams {
q.Orders = append(q.Orders, sqls.OrderByCol{Column: column, Asc: false})
return q
}
func (q *QueryParams) Limit(limit int) *QueryParams {
q.Page(1, limit)
return q
}
func (q *QueryParams) Page(page, limit int) *QueryParams {
if q.Paging == nil {
q.Paging = &sqls.Paging{Page: page, Limit: limit}
} else {
q.Paging.Page = page
q.Paging.Limit = limit
}
return q
}
+7 -7
View File
@@ -7,10 +7,10 @@ import (
"net/url"
"strings"
"cs-agent/internal/pkg/httpx/params"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/kataras/iris/v12"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/web/params"
)
// ExternalUser 外部访客身份(IM 客户),与站内 AuthPrincipal 区分。
@@ -26,7 +26,7 @@ type UserTokenClaims struct {
jwt.RegisteredClaims
}
func GetExternalUser(ctx iris.Context, secret string) (*ExternalUser, error) {
func GetExternalUser(ctx *gin.Context, secret string) (*ExternalUser, error) {
if userToken := getUserToken(ctx); strs.IsNotBlank(userToken) {
claims, err := verifyUserToken(userToken, secret)
if err != nil {
@@ -83,7 +83,7 @@ func verifyUserToken(userToken, secret string) (*UserTokenClaims, error) {
return claims, nil
}
func getUserToken(ctx iris.Context) string {
func getUserToken(ctx *gin.Context) string {
auth := strings.TrimSpace(ctx.GetHeader("Authorization"))
if len(auth) > 7 && strings.EqualFold(auth[:7], "Bearer ") {
if token := strings.TrimSpace(auth[7:]); token != "" {
@@ -94,7 +94,7 @@ func getUserToken(ctx iris.Context) string {
return strings.TrimSpace(userToken)
}
func getGuestUser(ctx iris.Context) (*ExternalUser, error) {
func getGuestUser(ctx *gin.Context) (*ExternalUser, error) {
externalID := getExternalID(ctx)
if strs.IsBlank(externalID) {
return nil, errorsx.Unauthorized("用户标识不能为空")
@@ -106,7 +106,7 @@ func getGuestUser(ctx iris.Context) (*ExternalUser, error) {
}, nil
}
func getExternalID(ctx iris.Context) string {
func getExternalID(ctx *gin.Context) string {
externalID := ctx.GetHeader("X-External-Id")
if strs.IsBlank(externalID) {
externalID, _ = params.Get(ctx, "externalId")
@@ -114,7 +114,7 @@ func getExternalID(ctx iris.Context) string {
return externalID
}
func getExternalName(ctx iris.Context) string {
func getExternalName(ctx *gin.Context) string {
externalName := ctx.GetHeader("X-External-Name")
if strs.IsBlank(externalName) {
externalName, _ = params.Get(ctx, "externalName")
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -6,7 +6,7 @@ import (
"time"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -5,7 +5,7 @@ import (
"cs-agent/internal/pkg/enums"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -6,7 +6,7 @@ import (
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -6,7 +6,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -6,7 +6,7 @@ import (
"time"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -6,7 +6,7 @@ import (
"strings"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"strings"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
@@ -4,7 +4,7 @@ import (
"cs-agent/internal/models"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"cs-agent/internal/pkg/httpx/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -11,8 +11,8 @@ import (
"strings"
"time"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var AgentProfileService = newAgentProfileService()
+1 -1
View File
@@ -5,8 +5,8 @@ import (
"cs-agent/internal/repositories"
"strings"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var AgentRunLogService = newAgentRunLogService()
@@ -14,8 +14,8 @@ import (
"sync"
"time"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
"gorm.io/gorm"
)
+1 -1
View File
@@ -11,8 +11,8 @@ import (
"strings"
"time"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var AgentTeamService = newAgentTeamService()
+1 -1
View File
@@ -15,8 +15,8 @@ import (
"cs-agent/internal/pkg/utils"
"cs-agent/internal/repositories"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var AIAgentService = newAIAgentService()
+1 -1
View File
@@ -12,9 +12,9 @@ import (
"cs-agent/internal/pkg/utils"
"cs-agent/internal/repositories"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var AIConfigService = newAIConfigService()
+10 -10
View File
@@ -17,7 +17,7 @@ import (
"strings"
"time"
"github.com/kataras/iris/v12"
"github.com/gin-gonic/gin"
"github.com/mlogclub/simple/common/strs"
"github.com/mlogclub/simple/sqls"
"golang.org/x/crypto/bcrypt"
@@ -37,18 +37,18 @@ func newAuthService() *authService {
type authService struct {
}
func (s *authService) GetAuthPrincipal(ctx iris.Context) *dto.AuthPrincipal {
func (s *authService) GetAuthPrincipal(ctx *gin.Context) *dto.AuthPrincipal {
if ctx == nil {
return nil
}
v := ctx.Values().Get(authPrincipalContextKey)
v, _ := ctx.Get(authPrincipalContextKey)
if principal, ok := v.(*dto.AuthPrincipal); ok {
return principal
}
return nil
}
func (s *authService) setAuthPrincipal(ctx iris.Context, user *models.User, roles, permissions []string) *dto.AuthPrincipal {
func (s *authService) setAuthPrincipal(ctx *gin.Context, user *models.User, roles, permissions []string) *dto.AuthPrincipal {
principal := &dto.AuthPrincipal{
UserID: user.ID,
Username: user.Username,
@@ -58,11 +58,11 @@ func (s *authService) setAuthPrincipal(ctx iris.Context, user *models.User, role
Roles: roles,
Permissions: permissions,
}
ctx.Values().Set(authPrincipalContextKey, principal)
ctx.Set(authPrincipalContextKey, principal)
return principal
}
func (s *authService) RequirePermission(ctx iris.Context, permission constants.Permission) (principal *dto.AuthPrincipal, err error) {
func (s *authService) RequirePermission(ctx *gin.Context, permission constants.Permission) (principal *dto.AuthPrincipal, err error) {
if principal = s.GetAuthPrincipal(ctx); principal == nil {
if principal, err = s.Authenticate(ctx); err != nil {
return nil, err
@@ -143,14 +143,14 @@ func (s *authService) Logout(accessToken string) error {
return nil
}
func (s *authService) Authenticate(ctx iris.Context) (*dto.AuthPrincipal, error) {
func (s *authService) Authenticate(ctx *gin.Context) (*dto.AuthPrincipal, error) {
if principal := s.GetAuthPrincipal(ctx); principal != nil {
return principal, nil
}
token := s.extractBearerToken(ctx.GetHeader("Authorization"))
if token == "" {
token = strings.TrimSpace(ctx.URLParam("accessToken"))
token = strings.TrimSpace(ctx.Query("accessToken"))
}
if token == "" {
return nil, errorsx.Unauthorized("未登录或登录已过期")
@@ -181,7 +181,7 @@ func (s *authService) Authenticate(ctx iris.Context) (*dto.AuthPrincipal, error)
return principal, nil
}
func (s *authService) HasPermission(ctx iris.Context, permissionCode string) bool {
func (s *authService) HasPermission(ctx *gin.Context, permissionCode string) bool {
principal := s.GetAuthPrincipal(ctx)
if principal == nil {
return false
@@ -189,7 +189,7 @@ func (s *authService) HasPermission(ctx iris.Context, permissionCode string) boo
return slices.Contains(principal.Permissions, permissionCode)
}
func (s *authService) CurrentProfile(ctx iris.Context) (*response.LoginResponse, error) {
func (s *authService) CurrentProfile(ctx *gin.Context) (*response.LoginResponse, error) {
principal, err := s.Authenticate(ctx)
if err != nil {
return nil, err
@@ -8,8 +8,8 @@ import (
"strings"
"time"
"cs-agent/internal/pkg/httpx/params"
"github.com/mlogclub/simple/sqls"
"github.com/mlogclub/simple/web/params"
)
var ChannelMessageOutboxService = newChannelMessageOutboxService()

Some files were not shown because too many files have changed in this diff Show More