Files
mayfly-go/server/initialize/router.go

46 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package initialize
import (
"fmt"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req"
"net/http"
"reflect"
"github.com/gin-gonic/gin"
)
// RouterApi
// 该接口的实现类注册到ioc中则会自动将请求配置注册到路由中
type RouterApi interface {
// ReqConfs 获取请求配置信息
ReqConfs() *req.Confs
}
type RouterConfig struct {
ContextPath string // 请求路径上下文
}
func InitRouter(router *gin.Engine, conf RouterConfig) *gin.Engine {
// 没有路由即 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)})
})
// 设置路由组
api := router.Group(conf.ContextPath + "/api")
// 获取所有实现了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)
}
}
return router
}