使用bee
工具
通过go get -u github.com/beego/bee/v2
安装,并将bee.exe配置到环境变量
当输入bee,可以看到如下信息
Bee is a Fast and Flexible tool for managing your Beego Web Application.
Usage:
bee command [arguments]
The commands are:
version show the bee & beego version
migrate run database migrations
api create an api application base on beego framework
bale packs non-Go files to Go source files
new create an application base on beego framework
run run the app which can hot compile
pack compress an beego project
fix Fixes your application by making it compatible with newer versions of Beego
dlv Start a debugging session using Delve
dockerize Generates a Dockerfile for your Beego application
generate Source code generator
hprose Creates an RPC application based on Hprose and Beego frameworks
pack Compresses a Beego application into a single file
rs Run customized scripts
run Run the application by starting a local development server
server serving static content over HTTP on port
Use bee help [command] for more information about a command.
新建项目
1、在src目录下使用命令bee new beegodemo
创建项目,如果没有go.mod文件,使用go mod init
初始化
目录架构如下所示:
quickstart
|-- conf
| `-- app.conf
|-- controllers
| `-- default.go
|-- main.go
|-- models
|-- routers
| `-- router.go
|-- static
| |-- css
| |-- img
| `-- js
|-- tests
| `-- default_test.go
`-- views
`-- index.tpl
main.go是入口文件,一个典型的MVC架构
go项目的执行方式
在router.go
文件中,web.Router
个函数的功能是映射 URL 到 controller,第一个参数是URL (用户请求的地址),这里我们注册的是/,也就是我们访问的不带任何参数的URL,第二个参数是对应的Controller,也就是我们即将把请求分发到那个控制器来执行相应的逻辑
这样用户就可以通过访问"/"
来执行MainController的逻辑
2、web.Run的执行过程
- 解析配置文件,conf包下的
app.conf
- 执行用户的hookfunc,用户可以通过
web.AddAPPStartHook()
注册自己的启动函数 - 是否开启session
- 是否编译模板
- 监听服务端口
Controller运行机制
通过声明结构体继承web.Controller
的所有方法,实现了一个控制器模块,而其中的方法,Post
,Get
,Delete
,Head
可以通过重写实现
beego是一个RESTful的框架,所以请求默认执行req.Method的方法
this.data
是一个用来存储输出数据的map,可以赋值任意类型的值,this.Tplname
就是需要渲染的模板,如果用户不设置,那么默认就回去Controller/<方法名>.tpl
查找
用户设置了模板后会自动调用Render
函数
当然也可以不使用模版,直接用 this.Ctx.WriteString
输出字符串
func (this*MainController)Get(){
this.Ctx.WriteString("hello")
}
model层一般用来处理数据库操作,如果应用足够简单,就不需要Model,如果模块增加,需要复用,需要逻辑分离,那么model是必不可少的
view编写
设置的模板文件,默认支持tpl
和html
的后缀名,goland是支持tpl文件的
在Controller中丢给data的数据,可以通过key来访问{{.key}}
静态文件处理
static的目录
├──static
│├── css
│├── img
│└── js
beego
默认注册了 static
目录为静态处理的目录
请问安装好之后没有自动生成那个bee.exe咋办