使用 API 级权限校验 - 可选

API 级校验接入后需要在后台进行配置对应权限, 同时服务端也需要进行一些简单接入。路由信息在运行 niuhe 插件生成的 API 后会自动添加到数据表中。使用权限校验需要两步处理

在 langs 中添加 route

src/niuhe/.config.json5 文件中的 langs 字段下添加路由信息 "route"。配置后会在 src/{app}/app/api/protos/gen_routes.go 中生成项目定义的路由信息。

将路由信息接入加入到 protocol 中

通过以下几行代码, 可将路由信息接入到 protocol 中。

routes := []*coreProtos.RouteItem{}
for _, route := range protos.RouteItems {
        routes = append(routes, &coreProtos.RouteItem{
                Method: route.Method,
                Path:   route.Path,
                Name:   route.Name,
        })
}
coreViews.GetProtocol().AddRoute("", routes)

接着上一节的内容, 结果 api 校验后的 views/init.go 文件内容如下:

package views

// Generated by niuhe.idl
import (
	"demo/app/api/protos"

	coreProtos "github.com/ma-guo/admin-core/app/v1/protos"
	coreViews "github.com/ma-guo/admin-core/app/v1/views"
	"github.com/ma-guo/niuhe"
)

var thisModule *niuhe.Module

func GetModule() *niuhe.Module {
	if thisModule == nil {
		// thisModule = niuhe.NewModule("api")
		// api 级权限处理
		routes := []*coreProtos.RouteItem{}
		for _, route := range protos.RouteItems {
			routes = append(routes, &coreProtos.RouteItem{
				Method: route.Method,
				Path:   route.Path,
				Name:   route.Name,
			})
		}
		coreViews.GetProtocol().AddRoute("", routes)

		coreViews.AddSkipUrl("/api/hellow/docs/") // 不需要认证的路径都加入到这里来
		thisModule = niuhe.NewModuleWithProtocolFactoryFunc("api", func() niuhe.IApiProtocol {
			return coreViews.GetProtocol() // 使用 coreViews 中定义的协议处理
		})
	}
	return thisModule
}