2021-04-16 15:10:07 +08:00
|
|
|
|
package initialize
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2021-07-28 18:03:19 +08:00
|
|
|
|
"fmt"
|
2024-12-16 23:29:18 +08:00
|
|
|
|
"mayfly-go/pkg/ioc"
|
|
|
|
|
|
"mayfly-go/pkg/req"
|
2021-07-28 18:03:19 +08:00
|
|
|
|
"net/http"
|
2024-12-16 23:29:18 +08:00
|
|
|
|
"reflect"
|
2021-04-16 15:10:07 +08:00
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-04-18 22:07:37 +08:00
|
|
|
|
// RouterApi
|
|
|
|
|
|
// 该接口的实现类注册到ioc中,则会自动将请求配置注册到路由中
|
2024-12-16 23:29:18 +08:00
|
|
|
|
type RouterApi interface {
|
|
|
|
|
|
// ReqConfs 获取请求配置信息
|
|
|
|
|
|
ReqConfs() *req.Confs
|
2024-01-22 11:35:28 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-04-18 22:07:37 +08:00
|
|
|
|
type RouterConfig struct {
|
|
|
|
|
|
ContextPath string // 请求路径上下文
|
|
|
|
|
|
}
|
2021-07-28 18:03:19 +08:00
|
|
|
|
|
2025-04-18 22:07:37 +08:00
|
|
|
|
func InitRouter(router *gin.Engine, conf RouterConfig) *gin.Engine {
|
2021-07-28 18:03:19 +08:00
|
|
|
|
// 没有路由即 404返回
|
|
|
|
|
|
router.NoRoute(func(g *gin.Context) {
|
|
|
|
|
|
g.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": fmt.Sprintf("not found '%s:%s'", g.Request.Method, g.Request.URL.Path)})
|
|
|
|
|
|
})
|
|
|
|
|
|
|
2021-04-16 15:10:07 +08:00
|
|
|
|
// 设置路由组
|
2025-04-18 22:07:37 +08:00
|
|
|
|
api := router.Group(conf.ContextPath + "/api")
|
2024-12-16 23:29:18 +08:00
|
|
|
|
|
|
|
|
|
|
// 获取所有实现了RouterApi接口的实例,并注册对应路由
|
|
|
|
|
|
ras := ioc.GetBeansByType[RouterApi](reflect.TypeOf((*RouterApi)(nil)).Elem())
|
|
|
|
|
|
for _, ra := range ras {
|
|
|
|
|
|
confs := ra.ReqConfs()
|
|
|
|
|
|
if group := confs.Group; group != "" {
|
|
|
|
|
|
req.BatchSetGroup(api.Group(group), confs.Confs)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
req.BatchSetGroup(api, confs.Confs)
|
|
|
|
|
|
}
|
2021-04-16 15:10:07 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return router
|
|
|
|
|
|
}
|