插件接口都在/interfaces文件目录下并有尽量详细的注释,你只需要查看interfaces目录下的文件接口就可以了解到linWeb的功能。
linWeb目前实现了请求上下文(context)、动态路由(router)、中间件(middleware)、模型验证与模型映射(model --- validate、map)等,其中部分实现参考了 极客兔兔的七天实现Web框架 。待开发功能及工作可在Roadmap中查看,欢迎建议、issue、pr和star~
在linWeb中,将完全面向接口编程并将可扩展部分插件化。
linWeb提供一套插件接口及默认实现,你也可以通过AddCustomizePlugins方法添加自定义实现。
使用NewLinWeb方法创建一个linWeb,调用Run方法就可以运行一个没有任何api的web项目。
func main() {
l := linWeb.NewLinWeb()
l.Run(":9999")
}
linWeb将面向Controller定义api接口。
①需要在controller方法的注释中添加注解,标识HTTP方法和路由路径。如果没有,将不作为一个http请求接口。
②方法的第一个参数必须为IContext,linWeb将自动实例化,Context中保存request及response的信息。
③如果存在dto入参,linWeb将自动解析request.body的json字符串,并将其转化为dto实例。
type LoginDto struct {
Name string `json:"Name"`
Password string `json:"Password"`
}
type UserController struct {
}
//[GET("/hello")]
func (user *UserController) Hello(c interfaces.IContext) {
c.Response().HTML(http.StatusOK, "<h1>Hello linWeb</h1>")
}
//[POST("/login")]
func (user *UserController) Login(c interfaces.IContext, dto LoginDto) {
fmt.Println(dto)
c.Response().String(http.StatusOK, "Welcome %s!", dto.Name)
}
func main() {
l := linWeb.NewLinWeb()
l.AddControllers(&controllers.UserController{}, &controllers.BlogController{})
l.Run(":9999")
}
使用AddMiddlewares方法添加多个针对所有api接口的全局中间件。
func main() {
l := linWeb.NewLinWeb()
l.AddMiddlewares(PrintHelloMiddleware)
l.AddControllers(&controllers.UserController{}, &controllers.BlogController{})
l.Run(":9999")
}
func PrintHelloMiddleware(c interfaces.IContext) {
fmt.Println("hello linWeb!")
c.Next()
fmt.Println("byebye linWeb")
}
可以通过AddCustomizePlugins方法添加自定义的插件(插件必须实现相应的接口),未添加的插件将使用默认插件。
func main() {
l := linWeb.NewLinWeb()
l.AddCustomizePlugins(&CustomizeModel{},&CustomizeRouter{})
l.AddControllers(&controllers.UserController{}, &controllers.BlogController{})
l.Run(":9999")
}
model用于对struct的模型验证与映射,采用链式调用的方式,可以通过NewModel方法传入需要操作的struct,通过调用Validate、MapToByFieldName等方法实现验证和Dto映射。目前使用validator、go-mapper实现验证与映射功能,使用规则详见链接。
type LoginDto struct {
Name string `json:"Name"`
Password string `json:"Password"`
}
type DatabaseModel struct {
Name string
Password string
}
type UserController struct {
}
//[POST("/login")]
func (user *UserController) Login(c interfaces.IContext, dto LoginDto) {
dataModel := &DatabaseModel{}
err := linweb.NewModel(dto).Validate().MapToByFieldName(dataModel).ModelError()
if err != nil {
c.Response().String(http.StatusInternalServerError, "Model error :%s!", err.Error())
}
c.Response().String(http.StatusOK, "Welcome %s!", dto.Name)
}