官方教程已经上线, 请访问: niuhe.zuxing.net/
在实际开发中, 有时我们需要对请求进行认证, 这时就需要一个钩子来处理请求认证; 或在数据返回前对数据进行统一处理等。在插件生成的 niuhe 代码中,是通过 IApiProtocol 来实现这个钩子的,IApiProtocol 的定义如下
type IApiProtocol interface {
Read(*Context, reflect.Value) error
Write(*Context, reflect.Value, error) error
}
其在 go niuhe 库中提供了一个默认实现:
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
}
在 admin-core 项目中, 提供了一个自定义实现
Bearea认证和修改默认返回的例子(报特定错误时显示为成功)