Post

beego 路由设置

路由注解

routers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // routers/routers.go
  package routers

  import (
    "lichaocheng/yun_mao/controllers"
    "github.com/astaxie/beego"
  )

  func init() {
    ns := beego.NewNamespace("/v1",
      beego.NSNamespace("/test",
        beego.NSInclude(
          &test.StatisticsController{},
        ),
      ),
    )
    beego.AddNamespace(ns)
  }

controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  package home

  import (
    "github.com/astaxie/beego"
  )

  type Test struct {
    beego.Controller
  }

  func (this *Test) URLMapping() {
    this.Mapping("Test", this.Test)
  }

  // Test TestCode
  // @Title test
  // @Description test
  // @Param	body 	true "test"
  // @Success 201
  // @Failure 403
  // @router /test/get/name [Post]
  func (this *Test) Test() {
      fmt.Println("Test")
  }

配置文件

1
2
conf/app.conf
EnableDocs=true

启动目录

bee run -gendoc=true -downdoc=true

生成commentsRouter*.go

注意事项

  • main.go 增加
1
2
3
4
    if beego.BConfig.RunMode == "dev" {
      beego.BConfig.WebConfig.DirectoryIndex = true
      beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
    }
  • 必须在gopath
    • route.go 注解路由运行是通过 CommentRouterPath 解析的,会在同文件下生成 commentsRouter_controllers.go 文件,但需要注意工程必须在 GOPATH 路径下,不然无法生成,也会无法匹配路由
    • 操作步骤
      • 如果是 go mod init test/testv1
      • export GO111MODULE=off
      • cd gopath/src
      • mkdir test
      • cd test
      • mkdir testv1
      • cp code .
      • bee run -gendoc=true -downdoc=true
      • cd router
      • ls grep “mmentsRouter”
      • cp 生成的文件 go mod 目录下
      • export GO111MODULE=on
      • bee run -gendoc=true -downdoc=true
      • 启动项目
This post is licensed under CC BY 4.0 by the author.