TOC

Beego 框架: 入门

照着官网文档 http://beego.vip 过一遍。
PS: 我之前看的网址是 beego.me, 不知道为啥换了域名。

前言

学习之前对于 Beego 的印象(根据相关资讯和知乎上看到的一些评价):

  1. 这不是一个拥有很多 Go 开发经验的人设计的框架,至少刚起步时是这样的。
    所以其中参考了很多可能来自其他语言(比如 Python 和 PHP)框架的设计。
  2. 这个框架对于 Go 在国内的推广起到来非常大的积极作用。
    PS: 据说在美国那边 Go 并不是很受欢迎,远不如在国内火爆。
  3. 模块化没有做的很好。PS: 2.x 开始在做拆分了。
    有些人认为 Beego 框架太重,这就是一个设计思路的差别了,没有什么。大而全 VS 小而美。

我的学习就直接从 v2 开始 (网上大部分资料还是基于 v1 的)。

开始

go get -u github.com/beego/beego/v2
go install github.com/beego/bee/v2@latest

# export | grep GOPATH
# 酌情添加:
echo 'export GOPATH="$HOME/go"' >> ~/.profile
echo 'export PATH="$GOPATH/bin:$PATH"' >> ~/.profile
source ~/.profile

cd /tmp
bee new hello # 创建应用
cd /tmp/hello
go get # 安装依赖

# markjour@dell:/tmp$ tree hello
# hello
# ├── conf              # 配置文件
# │   └── app.conf
# ├── controllers       # 控制器
# │   └── default.go
# ├── go.mod
# ├── go.sum
# ├── main.go
# ├── models            # 数据库模型
# ├── routers
# │   └── router.go
# ├── static            # 静态文件
# │   ├── css
# │   ├── img
# │   └── js
# │       └── reload.min.js
# ├── tests
# │   └── default_test.go
# └── views             # 视图(HTML 模板)
#     └── index.tpl
#
# 10 directories, 11 files

bee run # 测试,支持热重载(hot reload)

browse http://localhost:8080/

第一个控制器

controllers/default.go:

type HelloController struct {
    beego.Controller
}

func (c *HelloController) Get() {
    name := c.GetString("name", "world")
    c.Ctx.WriteString("hello " + name)
}

routers/router.go:

beego.Router("/hello", &controllers.HelloController{})

其他

lastupdate.tmp 是一个注解路由的缓存文件:

markjour@dell:/tmp/hello$ cat lastupdate.tmp | jq
{
  "/tmp/hello/controllers": 1641297824391445500
}