github: github.com/astaxie/beego
安装: go get github.com/astaxie/beego
package main
import (
"github.com/astaxie/beego/context"
"github.com/astaxie/beego"
)
func main(){
//1.12.* 版本
// 定义处理器
// 绑定URL和处理器功能 路由
// 基本路由
// 为 URL 绑定某个请求方法的路由函数
// 为根路径的GET方法绑定函数
beego.Get("/",func(ctx context.Context){ //Context是一个很重要的对象,请求和响应数据都要通过Context对象来获取
ctx.Output.Body([]byte("hi beego")) //responseWriter 的write函数类似S
})
beeego.Post("/POST",func(ctx *context.Context){ //常用的方法都可以直接使用 beego.${Method_Name}来实现
ctx.Output.Body([]byte("Post"))
})
beego.Any("/",func(ctx *context.Context){ //使用任何方法都可返回200,如果没有绑定any则返回404,绑定any则执行这一条规则。
ctx.Output.Body([]byte("any"))
})
// 正则路由 /delete/数值/1 => 数值解析到参数中
beego.Any(`/delete/:id/`,func(ctx *context.Context){ //:id为占位id,访问 /delete/123 可正常访问到页面;id可以通过 "ctx.Input.Param()来获取这个参数"
ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
})
beego.Any(`/delete/:id(\d{1,8})/`,func(ctx *context.Context){ //:id为占位id,访问 /delete/123 匹配1到8位的数字,超过,或不使用数字会返回404"
ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
})
beego.Any(`/delete/:id:int/)/`,func(ctx *context.Context){ // 通过类型去做限制"
ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
})
beego.Any("/user/*)/",func(ctx *context.Context){ // 访问任何/user/下的路径都会返回到user这个路径"
ctx.Output.Body([]byte("user:"+ ctx.Input.Param(":splat")))
})
beego.Any(`/file/*.*)/`,func(ctx *context.Context){ // 通过类型去做限制"
ctx.Output.Body([]byte("file:"+ ctx.Input.Param(":path"))) //拿到文件的路径
})
beego.Any(`/user/*`, func(ctx *context.Conttext){
ctx.Output.Body([]byte("user:" + ctx.Input.Param(":splat"))) //获得url后缀
})
//beego面向对象的格式(使用路由控制器,一个结构体,需要beego的Router函数来实现)
type HomeController struct{
beego.Controller
}
type UserController struct{
beego.Controller
}
func (c *Usercontroller) Get(){
c.Ctx.Output.Body(c.Ctx.Input.Param(":id"))
}
func (c *HomeController) Get(){
// 没有指定响应,会找views/homecontroller/get.tpl这个模板文件,如果没有这个文件返回500错误。
c.Ctx.Output.Body([]byte("HomeController.Get"))
}
//路由控制器
beego.Router("/home/",&HomeController{})
beego.Router(`/muser/:id(\d+)/`,&UserController{},"POST:Create;PUT:Modify;*:Any") //1、控制器使用正则的方法;2、使用POST代表Create方法,使用PUT代表Modify方法,注意,在明确标注方法后,没写到的方法调用会失败报错;Any代表其他方法,需要在struct里添加Any方法。
//一个url只能对应一个处理功能
//该示例用于展示自动路由功能
//Auth/Login
//auth/Logout
//auth为控制器名称,为访问前缀,大小写不敏感
type AuthController struct{
beego.Controller
}
func(c *Authcontroller)Login(){
}
func (c *Authcontroller) Logout(){
}
//自动路由
//自动路由不支持正则
beego.AutoRouter(&Authcontroller{})
// 启动服务
beego.Run() //启动beego
}
文档更新时间: 2023-07-11 16:36 作者:张尚