github: github.com/astaxie/beego
安装: go get github.com/astaxie/beego

  1. package main
  2. import (
  3. "github.com/astaxie/beego/context"
  4. "github.com/astaxie/beego"
  5. )
  6. func main(){
  7. //1.12.* 版本
  8. // 定义处理器
  9. // 绑定URL和处理器功能 路由
  10. // 基本路由
  11. // 为 URL 绑定某个请求方法的路由函数
  12. // 为根路径的GET方法绑定函数
  13. beego.Get("/",func(ctx context.Context){ //Context是一个很重要的对象,请求和响应数据都要通过Context对象来获取
  14. ctx.Output.Body([]byte("hi beego")) //responseWriter 的write函数类似S
  15. })
  16. beeego.Post("/POST",func(ctx *context.Context){ //常用的方法都可以直接使用 beego.${Method_Name}来实现
  17. ctx.Output.Body([]byte("Post"))
  18. })
  19. beego.Any("/",func(ctx *context.Context){ //使用任何方法都可返回200,如果没有绑定any则返回404,绑定any则执行这一条规则。
  20. ctx.Output.Body([]byte("any"))
  21. })
  22. // 正则路由 /delete/数值/1 => 数值解析到参数中
  23. beego.Any(`/delete/:id/`,func(ctx *context.Context){ //:id为占位id,访问 /delete/123 可正常访问到页面;id可以通过 "ctx.Input.Param()来获取这个参数"
  24. ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
  25. })
  26. beego.Any(`/delete/:id(\d{1,8})/`,func(ctx *context.Context){ //:id为占位id,访问 /delete/123 匹配1到8位的数字,超过,或不使用数字会返回404"
  27. ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
  28. })
  29. beego.Any(`/delete/:id:int/)/`,func(ctx *context.Context){ // 通过类型去做限制"
  30. ctx.Output.Body([]byte("delete:"+ ctx.Input.Param(":id")))
  31. })
  32. beego.Any("/user/*)/",func(ctx *context.Context){ // 访问任何/user/下的路径都会返回到user这个路径"
  33. ctx.Output.Body([]byte("user:"+ ctx.Input.Param(":splat")))
  34. })
  35. beego.Any(`/file/*.*)/`,func(ctx *context.Context){ // 通过类型去做限制"
  36. ctx.Output.Body([]byte("file:"+ ctx.Input.Param(":path"))) //拿到文件的路径
  37. })
  38. beego.Any(`/user/*`, func(ctx *context.Conttext){
  39. ctx.Output.Body([]byte("user:" + ctx.Input.Param(":splat"))) //获得url后缀
  40. })
  41. //beego面向对象的格式(使用路由控制器,一个结构体,需要beego的Router函数来实现)
  42. type HomeController struct{
  43. beego.Controller
  44. }
  45. type UserController struct{
  46. beego.Controller
  47. }
  48. func (c *Usercontroller) Get(){
  49. c.Ctx.Output.Body(c.Ctx.Input.Param(":id"))
  50. }
  51. func (c *HomeController) Get(){
  52. // 没有指定响应,会找views/homecontroller/get.tpl这个模板文件,如果没有这个文件返回500错误。
  53. c.Ctx.Output.Body([]byte("HomeController.Get"))
  54. }
  55. //路由控制器
  56. beego.Router("/home/",&HomeController{})
  57. beego.Router(`/muser/:id(\d+)/`,&UserController{},"POST:Create;PUT:Modify;*:Any") //1、控制器使用正则的方法;2、使用POST代表Create方法,使用PUT代表Modify方法,注意,在明确标注方法后,没写到的方法调用会失败报错;Any代表其他方法,需要在struct里添加Any方法。
  58. //一个url只能对应一个处理功能
  59. //该示例用于展示自动路由功能
  60. //Auth/Login
  61. //auth/Logout
  62. //auth为控制器名称,为访问前缀,大小写不敏感
  63. type AuthController struct{
  64. beego.Controller
  65. }
  66. funcc *AuthcontrollerLogin(){
  67. }
  68. func (c *Authcontroller) Logout(){
  69. }
  70. //自动路由
  71. //自动路由不支持正则
  72. beego.AutoRouter(&Authcontroller{})
  73. // 启动服务
  74. beego.Run() //启动beego
  75. }
文档更新时间: 2023-07-11 16:36   作者:张尚