官方教程已经上线, 请访问: http://niuhe.zuxing.net
在 admin-core 项目中, 提供了一个自定义实现Bearea
认证和修改默认返回的例子(报特定错误时显示为成功)
在实际开发场景里,对请求进行认证以及在数据返回前进行统一处理是常见的需求。例如,在开发企业级应用时,为确保系统安全性,需要对用户的每一次请求进行严格的身份认证;在数据展示前,为保证数据格式统一、符合业务需求,也需要对返回数据进行处理。这时,我们可以通过自定义 IApiProtocol
实现来达到这一目的。
在通过插件生成的 niuhe 代码中,IApiProtocol
扮演了统一处理参数的关键角色。它为处理请求认证和数据统一处理等操作提供了标准化的接口,您可以基于IApiProtocol
进行定制化开发,灵活满足不同业务场景下对请求和数据处理的多样化需求,从而使整个开发流程更加高效、规范。
在 niuhe 代码里,您只需实现 IApiProtocol
的 Read
和 Write
方法,前者处理输入数据,后者处理输出数据,再在 GetModule
返回自定义实现就行。
type IApiProtocol interface {
Read(*Context, reflect.Value) error
Write(*Context, reflect.Value, error) error
}
type DefaultApiProtocol struct{}
func (self DefaultApiProtocol) Read(c *Context, reqValue reflect.Value) error {
if err := zpform.ReadReflectedStructForm(c.Request, reqValue); err != nil {
return NewCommError(-1, err.Error())
}
return nil
}
func (self DefaultApiProtocol) Write(c *Context, rsp reflect.Value, err error) error {
rspInst := rsp.Interface()
if _, ok := rspInst.(isCustomRoot); ok {
c.JSON(200, rspInst)
} else {
var response map[string]interface{}
if err != nil {
if commErr, ok := err.(ICommError); ok {
response = map[string]interface{}{
"result": commErr.GetCode(),
"message": commErr.GetMessage(),
}
if commErr.GetCode() == 0 {
response["data"] = rsp.Interface()
}
} else {
response = map[string]interface{}{
"result": -1,
"message": err.Error(),
}
}
} else {
response = map[string]interface{}{
"result": 0,
"data": rspInst,
}
}
c.JSON(200, response)
}
return nil
}
下面代码片段展示自定义协议的引入示例
var thisModule *niuhe.Module
func GetModule() *niuhe.Module {
if thisModule == nil {
thisModule = niuhe.NewModule("api")
thisModule = niuhe.NewModuleWithProtocolFactoryFunc("api", func() niuhe.IApiProtocol {
return niuhe.DefaultApiProtocol{} // 自定义时替换掉本行即可
})
}
return thisModule
}