1、bee工具使用
bee 工具是一个为了协助快速开发 Beego 项目而创建的项目,通过 bee 你可以很容易的进行 Beego 项目的创
建、热编译、开发、测试、和部署。Bee工具可以使用的命令:
[root@zsx ~]# bee
2023/02/18 18:17:26.196 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
Bee is a Fast and Flexible tool for managing your Beego Web Application.You are using bee for beego v2.x. If you are working on beego v1.x, please downgrade version to bee v1.12.0USAGEbee command [arguments]AVAILABLE COMMANDSversion Prints the current Bee versionmigrate Runs database migrationsapi Creates a Beego API applicationbale Transforms non-Go files to Go source filesfix Fixes your application by making it compatible with newer versions of Beegopro Source code generatordev Commands which used to help to develop beego and beedlv Start a debugging session using Delvedockerize Generates a Dockerfile for your Beego applicationgenerate Source code generatorhprose Creates an RPC application based on Hprose and Beego frameworksnew Creates a Beego applicationpack Compresses a Beego application into a single filers Run customized scriptsrun Run the application by starting a local development serverserver serving static content over HTTP on portupdate Update BeeUse bee help [command] for more information about a command.ADDITIONAL HELP TOPICSUse bee help [topic] for more information about that topic.
可以使用bee help 命令
来查看某一个命令的具体使用方式。
1.1 new 命令
new
命令是新建一个 Web 项目,我们在命令行下执行 bee new <项目名>
就可以创建一个新的项目。但是注意该
命令必须在 $GOPATH/src
下执行,最后会在 $GOPATH/src
相应目录下生成项目结构。
该命令在上一篇我们已经演示过了。
# 帮助命令
[root@zsx beeuse]# bee help new
2023/02/18 18:27:11.411 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee new [appname] [-gopath=false] [-beego=v1.12.3]OPTIONS-beegoset beego version,only take effect by go mod-gopathSupport go path,default falseDESCRIPTIONCreates a Beego application for the given app name in the current directory.now defaults to generating as a go modules projectThe command 'new' creates a folder named [appname] [-gopath=false] [-beego=v1.12.3] and generates the following structure:├── main.go├── go.mod├── conf│ └── app.conf├── controllers│ └── default.go├── models├── routers│ └── router.go├── tests│ └── default_test.go├── static│ └── js│ └── css│ └── img└── views└── index.tpl
1.2 api命令
上面的 new
命令是用来新建 Web 项目,不过很多用户使用 beego 来开发 API 应用。所以这个 api
命令就是用
来创建 API 应用的,执行命令之后如下所示:
[root@zsx beeuse]# bee api apiproject
2023/02/18 18:30:16.017 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 18:30:16 INFO ▶ 0001 Generate api project support go modules.
2023/02/18 18:30:16 INFO ▶ 0002 Creating API...create /home/zhangshixing/go_work_space/src/beeuse/apiproject/go.modcreate /home/zhangshixing/go_work_space/src/beeuse/apiprojectcreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/confcreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllerscreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/testscreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/conf/app.confcreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/modelscreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/routers/create /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllers/object.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllers/user.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/tests/default_test.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/routers/router.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/models/object.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/models/user.gocreate /home/zhangshixing/go_work_space/src/beeuse/apiproject/main.go
2023/02/18 18:30:16 SUCCESS ▶ 0003 New API successfully created!
这个项目的目录结构如下:
[root@zsx beeuse]# tree apiproject/
apiproject/
├── conf
│ └── app.conf
├── controllers
│ ├── object.go
│ └── user.go
├── go.mod
├── main.go
├── models
│ ├── object.go
│ └── user.go
├── routers
│ └── router.go
└── tests└── default_test.go5 directories, 9 files
从上面的目录我们可以看到和 Web 项目相比,少了 static
和 views
目录,多了一个 test
模块,用来做单元
测试的。
# 帮助命令
[root@zsx beeuse]# bee help api
2023/02/18 18:31:51.315 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee api [appname]OPTIONS-beegoset beego version,only take effect by go mod-connConnection string used by the driver to connect to a database instance.-driverDatabase driver. Either mysql, postgres or sqlite.-gopathSupport go path,default false-tablesList of table names separated by a comma.DESCRIPTIONThe command 'api' creates a Beego API application.now default supoort generate a go modules project.Example:$ bee api [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-gopath=false] [-beego=v1.12.3]If 'conn' argument is empty, the command will generate an example API application. Otherwise the commandwill connect to your database and generate models based on the existing tables.The command 'api' creates a folder named [appname] with the following structure:├── main.go├── go.mod├── conf│ └── app.conf├── controllers│ └── object.go│ └── user.go├── routers│ └── router.go├── tests│ └── default_test.go└── models└── object.go└── user.go
同时,该命令还支持一些自定义参数自动连接数据库创建相关 model
和 controller
:
bee api [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]
如果conn参数为空则创建一个示例项目,否则将基于链接信息链接数据库创建项目。
[root@zsx beeuse]# bee api apidatabaseproject -tables="shop" -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/test"
2023/02/18 18:49:17.491 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 18:49:17 INFO ▶ 0001 Generate api project support go modules.
2023/02/18 18:49:17 INFO ▶ 0002 Creating API...create /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/go.modcreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseprojectcreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/confcreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/controllerscreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/testscreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/conf/app.confcreate /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/main.go
2023/02/18 18:49:17 INFO ▶ 0003 Using 'mysql' as 'driver'
2023/02/18 18:49:17 INFO ▶ 0004 Using 'root:root@tcp(127.0.0.1:3306)/test' as 'conn'
2023/02/18 18:49:17 INFO ▶ 0005 Using 'shop' as 'tables'
2023/02/18 18:49:17 INFO ▶ 0006 Analyzing database tables...
2023/02/18 18:49:17 INFO ▶ 0007 Creating model files...create /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/models/shop.go
2023/02/18 18:49:17 INFO ▶ 0008 Creating controller files...create /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/controllers/shop.go
2023/02/18 18:49:17 INFO ▶ 0009 Creating router files...create /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/routers/router.go
2023/02/18 18:49:17 SUCCESS ▶ 0010 New API successfully created!
目录结构如下:
[root@zsx beeuse]# tree apidatabaseproject/
apidatabaseproject/
├── conf
│ └── app.conf
├── controllers
│ └── shop.go
├── go.mod
├── main.go
├── models
│ └── shop.go
├── routers
│ └── router.go
└── tests5 directories, 6 files
1.3 run命令
我们在开发 Go 项目的时候最大的问题是经常需要自己手动去编译再运行,bee run
命令是监控 beego 的项目,
通过 [fsnotify]
https://github.com/howeyc/fsnotify
监控文件系统。但是注意该命令必须在
$GOPATH/src/appname
下执行。 这样我们在开发过程中就可以实时的看到项目修改之后的效果。
该命令在上一篇也已经演示过了。
# 帮助文档
[root@zsx beeuse]# bee help run
2023/02/18 18:51:41.872 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee run [appname] [watchall] [-main=*.go] [-downdoc=true] [-gendoc=true] [-vendor=true] [-e=folderToExclude] [-ex=extraPackageToWatch] [-tags=goBuildTags] [-runmode=BEEGO_RUNMODE]OPTIONS-downdocEnable auto-download of the swagger file if it does not exist.-e=[]List of paths to exclude.-ex=[]List of extra package to watch.-gendocEnable auto-generate the docs.-ldflagsSet the build ldflags. See: https://golang.org/pkg/go/build/-main=[]Specify main go files.-runargsExtra args to run application-runmodeSet the Beego run mode.-tagsSet the build tags. See: https://golang.org/pkg/go/build/-vendor=falseEnable watch vendor folder.DESCRIPTIONRun command will supervise the filesystem of the application for any changes, and recompile/restart it.
1.4 pack命令
pack
目录用来发布应用的时候打包,会把项目打包成 zip 包,这样我们部署的时候直接把打包之后的项目上传,
解压就可以部署了。
[root@zsx hello]# bee pack
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 18:56:04 INFO ▶ 0001 Packaging application on '/home/zhangshixing/go_work_space/src/beeuse/hello'...
2023/02/18 18:56:04 INFO ▶ 0002 Building application (hello)...
2023/02/18 18:56:04 INFO ▶ 0003 Using: GOOS=linux GOARCH=amd64
2023/02/18 18:56:05 SUCCESS ▶ 0004 Build Successful!
2023/02/18 18:56:05 INFO ▶ 0005 Writing to output: /home/zhangshixing/go_work_space/src/beeuse/hello/hello.tar.gz
2023/02/18 18:56:05 INFO ▶ 0006 Excluding relpath prefix: .
2023/02/18 18:56:05 INFO ▶ 0007 Excluding relpath suffix: .go:.DS_Store:.tmp:go.mod:go.sum
2023/02/18 18:56:06 SUCCESS ▶ 0008 Application packed!
我们可以看到目录下有如下的压缩文件:
[root@zsx hello]# ll
total 9648
drwxr-xr-x. 2 root root 22 Feb 18 18:55 conf
drwxr-xr-x. 2 root root 24 Feb 18 18:55 controllers
-rw-r--r--. 1 root root 1481 Feb 18 18:55 go.mod
-rw-r--r--. 1 root root 27732 Feb 18 18:55 go.sum
-rw-r--r--. 1 root root 9839467 Feb 18 18:56 hello.tar.gz
-rw-r--r--. 1 root root 121 Feb 18 18:55 main.go
drwxr-xr-x. 2 root root 6 Feb 18 18:55 models
drwxr-xr-x. 2 root root 23 Feb 18 18:55 routers
drwxr-xr-x. 5 root root 38 Feb 18 18:55 static
drwxr-xr-x. 2 root root 29 Feb 18 18:55 tests
drwxr-xr-x. 2 root root 23 Feb 18 18:55 views
# 帮助文档
[root@zsx beeuse]# bee help pack
2023/02/18 18:57:00.821 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee packOPTIONS-aSet the application name. Defaults to the dir name.-b=trueTell the command to do a build for the current platform. Defaults to true.-baSpecify additional args for Go build.-be=[]Specify additional env variables for Go build. e.g. GOARCH=arm.-exp=.Set prefixes of paths to be excluded. Uses a column (:) as separator.-exr=[]Set a regular expression of files to be excluded.-exs=.go:.DS_Store:.tmpSet suffixes of paths to be excluded. Uses a column (:) as separator.-f=tar.gzSet file format. Either tar.gz or zip. Defaults to tar.gz.-fs=falseTell the command to follow symlinks. Defaults to false.-oSet the compressed file output path. Defaults to the current path.-pSet the application path. Defaults to the current path.-ss=falseTell the command to skip symlinks. Defaults to false.-v=falseBe more verbose during the operation. Defaults to false.DESCRIPTIONPack is used to compress Beego applications into a tarball/zip file.This eases the deployment by directly extracting the file to a server.Example:$ bee pack -v -ba="-ldflags '-s -w'"
1.5 bale命令
这个命令目前仅限内部使用,具体实现方案未完善,主要用来压缩所有的静态文件变成一个变量申明文件,全部编
译到二进制文件里面,用户发布的时候携带静态文件,包括 js
、css
、img
和 views
。最后在启动运行时进行
非覆盖式的自解压。
[root@zsx hello]# bee bale
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 19:01:02 SUCCESS ▶ 0001 Baled resources successfully!
[root@zsx hello]# ll
total 9652
drwxr-xr-x. 2 root root 6 Feb 18 19:01 bale
-rw-r--r--. 1 root root 842 Feb 18 19:01 bale.go
drwxr-xr-x. 2 root root 22 Feb 18 18:55 conf
drwxr-xr-x. 2 root root 24 Feb 18 18:55 controllers
-rw-r--r--. 1 root root 1481 Feb 18 18:55 go.mod
-rw-r--r--. 1 root root 27732 Feb 18 18:55 go.sum
-rw-r--r--. 1 root root 9839467 Feb 18 18:56 hello.tar.gz
-rw-r--r--. 1 root root 121 Feb 18 18:55 main.go
drwxr-xr-x. 2 root root 6 Feb 18 18:55 models
drwxr-xr-x. 2 root root 23 Feb 18 18:55 routers
drwxr-xr-x. 5 root root 38 Feb 18 18:55 static
drwxr-xr-x. 2 root root 29 Feb 18 18:55 tests
drwxr-xr-x. 2 root root 23 Feb 18 18:55 views
# 帮助文档
[root@zsx beeuse]# bee help bale
2023/02/18 19:00:08.732 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee baleDESCRIPTIONBale command compress all the static files in to a single binary file.This is useful to not have to carry static files including js, css, images andviews when deploying a Web application.It will auto-generate an unpack function to the main package then run it during the runtime.This is mainly used for zealots who are requiring 100% Go code.
1.6 version命令
这个命令是动态获取 bee、beego 和 Go 的版本,这样一旦用户出现错误,可以通过该命令来查看当前的版本。
[root@zsx beeuse]# bee version
2023/02/18 19:02:43.302 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4├── GoVersion : go1.18.4
├── GOOS : linux
├── GOARCH : amd64
├── NumCPU : 1
├── GOPATH : /home/zhangshixing/go_work_space
├── GOROOT : /home/zhangshixing/go
├── Compiler : gc
└── Date : Saturday, 18 Feb 2023
需要注意的是,目前 bee version
会试图输出当前beego
的版本。
但是目前这个实现有点坑,它是通过读取$GOPATH/src/astaxie/beego
下的文件来进行的。
这意味着,如果你本地并没有下载beego
源码,或者放置的位置不对,bee
都无法输出beego
的版本信息。
# 帮助文档
[root@zsx beeuse]# bee help version
2023/02/18 19:03:11.332 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee versionOPTIONS-oSet the output format. Either json or yaml.DESCRIPTIONPrints the current Bee, Beego and Go version alongside the platform information.
1.7 generate命令
这个命令是用来自动化的生成代码的,包含了从数据库一键生成 model,还包含了 scaffold 的,通过这个命令,
让大家开发代码不再慢。
# 帮助文档
[root@zsx beeuse]# bee help generate
2023/02/18 19:04:58.950 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee generate [command]OPTIONS-connConnection string used by the SQLDriver to connect to a database instance.-ctrlDirController directory. Bee scans this directory and its sub directory to generate routers-ddlGenerate DDL Migration-driverDatabase SQLDriver. Either mysql, postgres or sqlite.-fieldsList of table Fields.-levelEither 1, 2 or 3. i.e. 1=models; 2=models and controllers; 3=models, controllers and routers.-routersFileRouters file. If not found, Bee create a new one. Bee will truncates this file and output routers info into this file-routersPkgrouter's package. Default is routers, it means that "package routers" in the generated file-tablesList of table names separated by a comma.DESCRIPTION▶ To scaffold out your entire application:$ bee generate scaffold [scaffoldname] [-fields="title:string,body:text"] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]▶ To generate a Model based on fields:$ bee generate model [modelname] [-fields="name:type"]▶ To generate a controller:$ bee generate controller [controllerfile]▶ To generate a CRUD view:$ bee generate view [viewpath]▶ To generate a migration file for making database schema updates:$ bee generate migration [migrationfile] [-fields="name:type"]▶ To generate swagger doc file:$ bee generate docs▶ To generate swagger doc file:$ bee generate routers [-ctrlDir=/path/to/controller/directory] [-routersFile=/path/to/routers/file.go] [-routersPkg=myPackage]▶ To generate a test case:$ bee generate test [routerfile]▶ To generate appcode based on an existing database:$ bee generate appcode [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-level=3]
1.7.1 generate scaffold
▶ To scaffold out your entire application:$ bee generate scaffold [scaffoldname] [-fields="title:string,body:text"] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]The generate scaffold command will do a number of things for you.-fields: a list of table fields. Format: field:type, ...-driver: [mysql | postgres | sqlite], the default is mysql-conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/testexample: bee generate scaffold post -fields="title:string,body:text"
第一步创建表:
CREATE TABLE `test`.`user`( `id` INT(11) NOT NULL AUTO_INCREMENT,`name` VARCHAR(20),`gender` TINYINT(1),`age` TINYINT(3),PRIMARY KEY (`id`)
);
第二步使用bee generate自动生成代码:
bee generate scaffold user -fields="id:int64,name:string,gender:int,age:int" -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/test"
说明:
-
scaffold
:脚手架 -
user
:是表名 -
-fields
:是表字段名,字段名冒号类型逗号 -
-driver
:驱动类型 -
-conn
:连接信息
[root@zsx beeuse]# mkdir scaffoldproject
[root@zsx beeuse]# cd scaffoldproject/
[root@zsx scaffoldproject]# bee generate scaffold user -fields="id:int64,name:string,gender:int,age:int" -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/test"
2023/02/18 19:14:21.782 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 19:14:21 INFO ▶ 0001 Do you want to create a 'user' model? [Yes|No]
yes
2023/02/18 19:14:23 INFO ▶ 0002 Using 'User' as model name
2023/02/18 19:14:23 INFO ▶ 0003 Using 'models' as package namecreate /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/models/user.go
2023/02/18 19:14:23 INFO ▶ 0004 Do you want to create a 'user' controller? [Yes|No]
yes
2023/02/18 19:14:24 INFO ▶ 0005 Using 'User' as controller name
2023/02/18 19:14:24 INFO ▶ 0006 Using 'controllers' as package name
2023/02/18 19:14:24 INFO ▶ 0007 Using matching model 'User'create /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/controllers/user.go
2023/02/18 19:14:24 INFO ▶ 0008 Do you want to create views for this 'user' resource? [Yes|No]
yes
2023/02/18 19:14:27 INFO ▶ 0009 Generating view...create /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/index.tplcreate /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/show.tplcreate /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/create.tplcreate /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/edit.tpl
2023/02/18 19:14:27 INFO ▶ 0010 Do you want to create a 'user' migration and schema for this resource? [Yes|No]
no
2023/02/18 19:14:29 INFO ▶ 0011 Do you want to migrate the database? [Yes|No]
no
2023/02/18 19:14:30 SUCCESS ▶ 0012 All done! Don't forget to add beego.Router("/user" ,&controllers.UserController{}) to routers/route.go2023/02/18 19:14:30 SUCCESS ▶ 0013 Scaffold successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree scaffoldproject/
scaffoldproject/
├── controllers
│ └── user.go
├── models
│ └── user.go
└── views└── user├── create.tpl├── edit.tpl├── index.tpl└── show.tpl4 directories, 6 files
第三步执行命令:
[root@zsx scaffoldproject]# go mod init
[root@zsx scaffoldproject]# go mod tidy
1.7.2 generate model
▶ To generate a Model based on fields:$ bee generate model [modelname] [-fields="name:type"]generate RESTful model based on fields-fields: a list of table fields. Format: field:type, ...
# User是实体类的名字
[root@zsx beeuse]# mkdir modelproject
[root@zsx beeuse]# cd modelproject/
[root@zsx modelproject]# bee generate model User -fields="id:int64,name:string,gender:int,age:int"
2023/02/18 19:19:15.892 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 19:19:15 INFO ▶ 0001 Using 'User' as model name
2023/02/18 19:19:15 INFO ▶ 0002 Using 'models' as package namecreate /home/zhangshixing/go_work_space/src/beeuse/modelproject/models/user.go
2023/02/18 19:19:15 SUCCESS ▶ 0003 Model successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree modelproject/
modelproject/
└── models└── user.go1 directory, 1 file
1.7.3 generate controller
▶ To generate a controller:$ bee generate controller [controllerfile]generate RESTful controllers
[root@zsx beeuse]# mkdir controllerproject
[root@zsx beeuse]# cd controllerproject/
[root@zsx controllerproject]# bee generate controller UserController
2023/02/18 20:09:26.104 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 20:09:26 INFO ▶ 0001 Using 'UserController' as controller name
2023/02/18 20:09:26 INFO ▶ 0002 Using 'controllers' as package namecreate /home/zhangshixing/go_work_space/src/beeuse/controllerproject/controllers/usercontroller.go
2023/02/18 20:09:26 SUCCESS ▶ 0003 Controller successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree controllerproject/
controllerproject/
└── controllers└── usercontroller.go1 directory, 1 file
1.7.4 generate view
▶ To generate a CRUD view:$ bee generate view [viewpath]generate CRUD view in viewpath
[root@zsx beeuse]# mkdir viewproject
[root@zsx beeuse]# cd viewproject/
[root@zsx viewproject]# bee generate view UserView
2023/02/18 20:11:43.725 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 20:11:43 INFO ▶ 0001 Generating view...create /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/index.tplcreate /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/show.tplcreate /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/create.tplcreate /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/edit.tpl
2023/02/18 20:11:43 SUCCESS ▶ 0002 View successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree viewproject/
viewproject/
└── views└── UserView├── create.tpl├── edit.tpl├── index.tpl└── show.tpl2 directories, 4 files
1.7.5 generate migration
▶ To generate a migration file for making database schema updates:$ bee generate migration [migrationfile] [-fields="name:type"]generate migration file for making database schema update-fields: a list of table fields. Format: field:type, ...
[root@zsx beeuse]# mkdir migrationproject
[root@zsx beeuse]# cd migrationproject/
[root@zsx migrationproject]# bee generate migration User
2023/02/18 20:19:47.794 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 20:19:47 INFO ▶ 0001 Using 'User' as migration namecreate /home/zhangshixing/go_work_space/src/beeuse/migrationproject/database/migrations/20230218_201947_User.go
2023/02/18 20:19:47 SUCCESS ▶ 0002 Migration successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree migrationproject/
migrationproject/
└── database└── migrations└── 20230218_201947_User.go2 directories, 1 file
1.7.6 generate routers
generate routers
是从原来beego
中剥离出来的功能。在早期,beego
的项目必须在启动的时候才会触发生成
路由文件。
现在我们把这个东西挪了出来,那么用户可以有更好的控制感。
bee generate routers [-ctrlDir=/path/to/controller/directory] [-routersFile=/path/to/routers/file.go] [-routersPkg=myPackage]-ctrlDir: the directory contains controllers definition. Bee scans this directory and its subdirectory to generate routers info-routersFile: output file. All generated routers info will be output into this file.If file not found, Bee create new one, or Bee truncates it.The default value is "routers/commentRouters.go"-routersPkg: package declaration.The default value is "routers".When you pass routersFile parameter, youd better pass this parameter
1、新建一个项目
[root@zsx src]# bee new swaggerdemo
2023/02/18 21:52:20.658 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
2023/02/18 21:52:20 INFO ▶ 0001 Generate new project support go modules.
2023/02/18 21:52:20 INFO ▶ 0002 Creating application...create /home/zhangshixing/go_work_space/src/swaggerdemo/go.modcreate /home/zhangshixing/go_work_space/src/swaggerdemo/create /home/zhangshixing/go_work_space/src/swaggerdemo/conf/create /home/zhangshixing/go_work_space/src/swaggerdemo/controllers/create /home/zhangshixing/go_work_space/src/swaggerdemo/models/create /home/zhangshixing/go_work_space/src/swaggerdemo/routers/create /home/zhangshixing/go_work_space/src/swaggerdemo/tests/create /home/zhangshixing/go_work_space/src/swaggerdemo/static/create /home/zhangshixing/go_work_space/src/swaggerdemo/static/js/create /home/zhangshixing/go_work_space/src/swaggerdemo/static/css/create /home/zhangshixing/go_work_space/src/swaggerdemo/static/img/create /home/zhangshixing/go_work_space/src/swaggerdemo/views/create /home/zhangshixing/go_work_space/src/swaggerdemo/conf/app.confcreate /home/zhangshixing/go_work_space/src/swaggerdemo/controllers/default.gocreate /home/zhangshixing/go_work_space/src/swaggerdemo/views/index.tplcreate /home/zhangshixing/go_work_space/src/swaggerdemo/routers/router.gocreate /home/zhangshixing/go_work_space/src/swaggerdemo/tests/default_test.gocreate /home/zhangshixing/go_work_space/src/swaggerdemo/main.go
2023/02/18 21:52:20 SUCCESS ▶ 0003 New application successfully created![root@zsx swaggerdemo]# go mod tidy
2、修改controllers/default.go
package controllersimport (beego "github.com/beego/beego/v2/server/web"
)type MainController struct {beego.Controller
}func (c *MainController) URLMapping() {c.Mapping("StaticBlock", c.StaticBlock)c.Mapping("AllBlock", c.AllBlock)c.Mapping("NoneBlock", c.NoneBlock)}// @router /static/:key [get]
func (this *MainController) StaticBlock() {this.Ctx.WriteString("StaticBlock!")
}// @router /all/:key [get]
func (this *MainController) AllBlock() {this.Ctx.WriteString("AllBlock!")}// @router /none [get]
func (this *MainController) NoneBlock() {this.Ctx.WriteString("NoneBlock!")}
3、修改routers/router.go
:
package routersimport ("swaggerdemo/controllers"beego "github.com/beego/beego/v2/server/web"
)func init() {beego.Include(&controllers.MainController{})
}
4、生成routers
默认项目会自动生成/routers/commentsRouter_controllers.go
,这里也可以自己生成。
[root@zsx swaggerdemo]# bee generate routers
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 22:11:34 INFO ▶ 0001 input parameter: [routers]
2023/02/18 22:11:34 INFO ▶ 0002 read controller info from directory[controllers], and output routers to [routers/commentsRouter.go]
2023/02/18 22:11:34.639 [I] [gen_routes.go:421] generate router from comments
2023/02/18 22:11:34 INFO ▶ 0003 using routers as routers file's package
2023/02/18 22:11:34 SUCCESS ▶ 0004 Routers successfully generated!
[root@zsx swaggerdemo]# ls routers/
commentsRouter_controllers.go commentsRouter.go router.go
也可以指定自己生成的地方:
[root@zsx beeuse]# mkdir routersproject
[root@zsx beeuse]# cd routersproject/
[root@zsx routersproject]# bee generate routers -ctrlDir=/home/zhangshixing/go_work_space/src/swaggerdemo/controllers/ -routersFile=$GOPATH/src/beeuse/routersproject//routercomments.go -routersPkg=mypackage
2023/02/18 22:13:46.178 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 22:13:46 INFO ▶ 0001 input parameter: [routers -ctrlDir=/home/zhangshixing/go_work_space/src/swaggerdemo/controllers/ -routersFile=/home/zhangshixing/go_work_space/src/beeuse/routersproject//routercomments.go -routersPkg=mypackage]
2023/02/18 22:13:46 INFO ▶ 0002 read controller info from directory[/home/zhangshixing/go_work_space/src/swaggerdemo/controllers/], and output routers to [/home/zhangshixing/go_work_space/src/beeuse/routersproject//routercomments.go]
2023/02/18 22:13:46.509 [I] generate router from comments
2023/02/18 22:13:46 INFO ▶ 0003 using mypackage as routers file's package
2023/02/18 22:13:46 SUCCESS ▶ 0004 Routers successfully generated!
[root@zsx routersproject]# ll
total 4
-rw-r--r--. 1 root root 1336 Feb 18 22:13 routercomments.go
1.7.7 generate docs
▶ To generate swagger doc file:$ bee generate docs▶ To generate swagger doc file:$ bee generate routers [-ctrlDir=/path/to/controller/directory] [-routersFile=/path/to/routers/file.go] [-routersPkg=myPackage]
在上一小节的项目的基础上进行修改。
1、修改routers/router.go
:
// @APIVersion 1.0.0
// @Title Test API
// @Description beego has a very cool tools to autogenerate documents for your API
// @Contact qingyue@gmail.com
// @TermsOfServiceUrl http://beego.me/
// @License Apache 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
package routersimport ("swaggerdemo/controllers"beego "github.com/beego/beego/v2/server/web"
)func init() {ns := beego.NewNamespace("/v1",beego.NSNamespace("/main",beego.NSInclude(&controllers.MainController{},),),)beego.AddNamespace(ns)beego.Router("/v1/main/static/:key", &controllers.MainController{}, "get:StaticBlock")beego.Router("/v1/main/all/:key", &controllers.MainController{}, "get:AllBlock")beego.Router("/v1/main/none", &controllers.MainController{}, "get:NoneBlock")beego.SetStaticPath("/swagger", "swagger")
}
2、修改conf/app.conf
文件,添加EnableDocs = true
配置,开启文档自动生成。
3、修改controllers/default.go
文件添加swagger
注释:
package controllersimport (beego "github.com/beego/beego/v2/server/web"
)type MainController struct {beego.Controller
}func (c *MainController) URLMapping() {c.Mapping("StaticBlock", c.StaticBlock)c.Mapping("AllBlock", c.AllBlock)c.Mapping("NoneBlock", c.NoneBlock)}// @Title StaticBlock
// @Description find object by StaticBlock
// @Param key path string true "the objectid you want to get"
// @Success 200 {string} find object success
// @Failure 403 :key is empty
// @router /static/:key [get]
func (this *MainController) StaticBlock() {this.Ctx.WriteString("StaticBlock!")
}// @Title AllBlock
// @Description find object by AllBlock
// @Param key path string true "the objectid you want to get"
// @Success 200 {string} find object success
// @Failure 403 :key is empty
// @router /all/:key [get]
func (this *MainController) AllBlock() {this.Ctx.WriteString("AllBlock!")}// @Title NoneBlock
// @Description find object by NoneBlock
// @Success 200 {string} find object success
// @Failure 403 {string} find object failure
// @router /none [get]
func (this *MainController) NoneBlock() {this.Ctx.WriteString("NoneBlock!")}
4、生成
[root@zsx swaggerdemo]# bee generate docs
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 22:16:23 SUCCESS ▶ 0001 Docs successfully generated!
[root@zsx swaggerdemo]# ll
total 18024
drwxr-xr-x. 2 root root 22 Feb 18 21:52 conf
drwxr-xr-x. 2 root root 24 Feb 18 21:52 controllers
-rw-r--r--. 1 root root 1487 Feb 18 21:52 go.mod
-rw-r--r--. 1 root root 27732 Feb 18 21:52 go.sum
-rw-r--r--. 1 root root 127 Feb 18 21:52 main.go
drwxr-xr-x. 2 root root 6 Feb 18 21:52 models
drwxr-xr-x. 2 root root 85 Feb 18 22:11 routers
drwxr-xr-x. 5 root root 38 Feb 18 21:52 static
drwxr-xr-x. 2 root root 45 Feb 18 22:16 swagger
drwxr-xr-x. 2 root root 29 Feb 18 21:52 tests
drwxr-xr-x. 2 root root 23 Feb 18 21:52 views
swagger
是新生成的目录,内容如下:
[root@zsx swaggerdemo]# ls swagger
swagger.json swagger.yml
查看swagger.json
文件的内容:
{"swagger": "2.0","info": {"title": "Test API","description": "beego has a very cool tools to autogenerate documents for your API\n","version": "1.0.0","termsOfService": "http://beego.me/","contact": {"email": "qingyue@gmail.com"},"license": {"name": "Apache 2.0","url": "http://www.apache.org/licenses/LICENSE-2.0.html"}},"basePath": "/v1","paths": {"/main/all/{key}": {"get": {"tags": ["main"],"description": "find object by AllBlock\n\u003cbr\u003e","operationId": "MainController.AllBlock","parameters": [{"in": "path","name": "key","description": "the objectid you want to get","required": true,"type": "string"}],"responses": {"200": {"description": "{string} find object success"},"403": {"description": ":key is empty"}}}},"/main/none": {"get": {"tags": ["main"],"description": "find object by NoneBlock\n\u003cbr\u003e","operationId": "MainController.NoneBlock","responses": {"200": {"description": "{string} find object success"},"403": {"description": "{string} find object failure"}}}},"/main/static/{key}": {"get": {"tags": ["main"],"description": "find object by StaticBlock\n\u003cbr\u003e","operationId": "MainController.StaticBlock","parameters": [{"in": "path","name": "key","description": "the objectid you want to get","required": true,"type": "string"}],"responses": {"200": {"description": "{string} find object success"},"403": {"description": ":key is empty"}}}}}
}
5、启动项目并自动生成加载swagger
[root@zsx swaggerdemo]# bee run -gendoc=true -downdoc=true
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 22:17:22 INFO ▶ 0001 Using 'swaggerdemo' as 'appname'
2023/02/18 22:17:22 INFO ▶ 0002 Downloading 'https://codeload.github.com/beego/swagger/zip/refs/tags/v4.6.1' to 'swagger.zip'...
2023/02/18 22:17:25 SUCCESS ▶ 0003 3065067 bytes downloaded!
2023/02/18 22:17:25 INFO ▶ 0004 Unzipping 'swagger.zip'...
2023/02/18 22:17:25 SUCCESS ▶ 0005 Done! Deleting 'swagger.zip'...
2023/02/18 22:17:25 INFO ▶ 0006 Initializing watcher...
2023/02/18 22:17:25 INFO ▶ 0007 Generating the docs...
2023/02/18 22:17:25 SUCCESS ▶ 0008 Docs generated!
2023/02/18 22:17:27 SUCCESS ▶ 0009 Built Successfully!
2023/02/18 22:17:27 INFO ▶ 0010 Restarting 'swaggerdemo'...
2023/02/18 22:17:27 SUCCESS ▶ 0011 './swaggerdemo' is running...
2023/02/18 22:17:27.026 [I] [parser.go:85] /home/zhangshixing/go_work_space/src/swaggerdemo/controllers no changed2023/02/18 22:17:27.026 [I] [server.go:241] http server Running on http://:8080
swagger
目录下新生成了许多文件:
[root@zsx swaggerdemo]# ls swagger
favicon-16x16.png swagger-ui-bundle.js.map swagger-ui.js.map
favicon-32x32.png swagger-ui.css swagger-ui-standalone-preset.js
index.html swagger-ui.css.map swagger-ui-standalone-preset.js.map
oauth2-redirect.html swagger-ui-es-bundle-core.js swagger.yml
swagger.json swagger-ui-es-bundle.js
swagger-ui-bundle.js swagger-ui.js
6、停掉项目,修改swagger/index.html
文件:
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script>window.onload = function() {// Build a systemconst ui = SwaggerUIBundle({url: "swagger.json",validatorUrl: false,dom_id: '#swagger-ui',presets: [SwaggerUIBundle.presets.apis,SwaggerUIStandalonePreset],plugins: [SwaggerUIBundle.plugins.DownloadUrl],layout: "StandaloneLayout"})window.ui = ui}
</script>
7、重新启动项目
[root@zsx swaggerdemo]# bee run -gendoc=true -downdoc=true
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 09:59:18 INFO ▶ 0001 Using 'swaggerdemo' as 'appname'
2023/02/19 09:59:18 INFO ▶ 0002 Initializing watcher...
2023/02/19 09:59:19 INFO ▶ 0003 Generating the docs...
2023/02/19 09:59:19 SUCCESS ▶ 0004 Docs generated!
2023/02/19 09:59:20 SUCCESS ▶ 0005 Built Successfully!
2023/02/19 09:59:20 INFO ▶ 0006 Restarting 'swaggerdemo'...
2023/02/19 09:59:20 SUCCESS ▶ 0007 './swaggerdemo' is running...
2023/02/19 09:59:20.924 [I] [parser.go:413] generate router from comments2023/02/19 09:59:20.935 [I] [server.go:241] http server Running on http://:8080
8、访问路径http://127.0.0.1:8080/swagger/
:
访问v1/main/none
:
访问v1/main/all:key
:
整个项目的结构:
[root@zsx src]# tree swaggerdemo/
swaggerdemo/
├── conf
│ └── app.conf
├── controllers
│ └── default.go
├── go.mod
├── go.sum
├── main.go
├── models
├── routers
│ ├── commentsRouter_controllers.go
│ ├── commentsRouter.go
│ └── router.go
├── static
│ ├── css
│ ├── img
│ └── js
│ └── reload.min.js
├── swagger
│ ├── favicon-16x16.png
│ ├── favicon-32x32.png
│ ├── index.html
│ ├── oauth2-redirect.html
│ ├── swagger.json
│ ├── swagger-ui-bundle.js
│ ├── swagger-ui-bundle.js.map
│ ├── swagger-ui.css
│ ├── swagger-ui.css.map
│ ├── swagger-ui-es-bundle-core.js
│ ├── swagger-ui-es-bundle.js
│ ├── swagger-ui.js
│ ├── swagger-ui.js.map
│ ├── swagger-ui-standalone-preset.js
│ ├── swagger-ui-standalone-preset.js.map
│ └── swagger.yml
├── tests
│ └── default_test.go
└── views└── index.tpl11 directories, 27 files
1.7.8 generate test
▶ To generate a test case:$ bee generate test [routerfile]generate testcase
该命令在高版本中已经被移除。
[root@zsx beeuse]# mkdir testproject
[root@zsx beeuse]# cd testproject/
[root@zsx testproject]# bee generate test router.go
2023/02/19 10:24:35.854 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 10:24:35 FATAL ▶ 0001 Command is missing
1.7.9 generate appcode
▶ To generate appcode based on an existing database:$ bee generate appcode [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-level=3]generate appcode based on an existing database-tables: a list of table names separated by ',', default is empty, indicating all tables-driver: [mysql | postgres | sqlite], the default is mysql-conn: the connection string used by the driver.default for mysql: root:@tcp(127.0.0.1:3306)/testdefault for postgres: postgres://postgres:postgres@127.0.0.1:5432/postgres-level: [1 | 2 | 3], 1 = models; 2 = models,controllers; 3 = models,controllers,router
[root@zsx beeuse]# mkdir appcodeproject
[root@zsx beeuse]# cd appcodeproject/
[root@zsx appcodeproject]# bee generate appcode -tables="user" -driver=mysql -conn="root:root@tcp(127.0.0.1:3306)/test" -level=3
2023/02/19 10:28:21.658 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 10:28:21 INFO ▶ 0001 Using 'mysql' as 'SQLDriver'
2023/02/19 10:28:21 INFO ▶ 0002 Using 'root:root@tcp(127.0.0.1:3306)/test' as 'SQLConn'
2023/02/19 10:28:21 INFO ▶ 0003 Using 'user' as 'Tables'
2023/02/19 10:28:21 INFO ▶ 0004 Using '3' as 'Level'
2023/02/19 10:28:21 INFO ▶ 0005 Analyzing database tables...
2023/02/19 10:28:21 INFO ▶ 0006 Creating model files...create /home/zhangshixing/go_work_space/src/beeuse/appcodeproject/models/user.go
2023/02/19 10:28:21 INFO ▶ 0007 Creating controller files...create /home/zhangshixing/go_work_space/src/beeuse/appcodeproject/controllers/user.go
2023/02/19 10:28:21 INFO ▶ 0008 Creating router files...create /home/zhangshixing/go_work_space/src/beeuse/appcodeproject/routers/router.go
2023/02/19 10:28:21 SUCCESS ▶ 0009 Appcode successfully generated!
生成的目录结构:
[root@zsx beeuse]# tree appcodeproject/
appcodeproject/
├── controllers
│ └── user.go
├── models
│ └── user.go
└── routers└── router.go3 directories, 3 files
1.8 migrate命令
这个命令是应用的数据库迁移命令,主要是用来每次应用升级,降级的SQL管理。
# 帮助文档
[root@zsx beeuse]# bee help migrate
2023/02/19 10:30:39.943 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee migrate [Command]OPTIONS-connConnection string used by the driver to connect to a database instance.-dirThe directory where the migration files are stored-driverDatabase driver. Either mysql, postgres or sqlite.DESCRIPTIONThe command 'migrate' allows you to run database migrations to keep it up-to-date.▶ To run all the migrations:$ bee migrate [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-dir="path/to/migration"]▶ To rollback the last migration:$ bee migrate rollback [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-dir="path/to/migration"]▶ To do a reset, which will rollback all the migrations:$ bee migrate reset [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-dir="path/to/migration"]▶ To update your schema:$ bee migrate refresh [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-dir="path/to/migration"]
命令参数:
bee migrate [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]run all outstanding migrations-driver: [mysql | postgresql | sqlite], the default is mysql-conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/testbee migrate rollback [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]rollback the last migration operation-driver: [mysql | postgresql | sqlite], the default is mysql-conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/testbee migrate reset [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]rollback all migrations-driver: [mysql | postgresql | sqlite], the default is mysql-conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/testbee migrate refresh [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]rollback all migrations and run them all again-driver: [mysql | postgresql | sqlite], the default is mysql-conn: the connection string used by the driver, the default is root:@tcp(127.0.0.1:3306)/test
使用例子:
1、生成迁移文件
[root@zsx beeuse]# mkdir migrateproject
[root@zsx beeuse]# cd migrateproject/
# 命令格式
# bee generate migration [migrationfile] [-fields="name:type"]
[root@zsx migrateproject]# bee generate migration Student
2023/02/19 10:55:03.429 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 10:55:03 INFO ▶ 0001 Using 'Student' as migration namecreate /home/zhangshixing/go_work_space/src/beeuse/migrateproject/database/migrations/20230219_105503_Student.go
2023/02/19 10:55:03 SUCCESS ▶ 0002 Migration successfully generated!
2、完成迁移脚本
[root@zsx migrateproject]# ls database/migrations/
20230219_105503_Student.go
[root@zsx migrateproject]# vim database/migrations/20230219_105503_Student.go
package mainimport ("fmt""github.com/beego/beego/v2/client/orm/migration"
)// DO NOT MODIFY
type Student_20230219_105503 struct {migration.Migration
}// DO NOT MODIFY
func init() {m := &Student_20230219_105503{}m.Created = "20230219_105503"migration.Register("Student_20230219_105503", m)
}// Run the migrations
func (m *Student_20230219_105503) Up() {// use m.SQL("CREATE TABLE ...") to make schema updatem.CreateTable("Student", "innodb", "utf8mb4")m.PriCol("id").SetAuto(true).SetDataType("int(11)").SetUnsigned(true)m.NewCol("nickname").SetDataType("varchar(255)").SetNullable(false)m.NewCol("avatar").SetDataType("varchar(32)").SetDefault("''").SetNullable(false)m.NewCol("status").SetDataType("tinyint(1)").SetUnsigned(true).SetDefault("1").SetNullable(false)m.NewCol("created_at").SetDataType("timestamp").SetDefault("NOW()").SetNullable(false)fmt.Println("SQL: ", m.GetSQL())m.SQL(m.GetSQL())
}// Reverse the migrations
func (m *Student_20230219_105503) Down() {// use m.SQL("DROP TABLE ...") to reverse schema updatem.SQL("DROP TABLE IF EXISTS Student")
}
此处注意默认空字符的写法,SetDefault("''")
。
3、执行迁移命令
[root@zsx migrateproject]# go mod init
[root@zsx migrateproject]# go mod tidy
# 命令格式
# bee migrate [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"] [-dir="path/to/migration"]
[root@zsx migrateproject]# bee migrate -conn="root:root@tcp(127.0.0.1:3306)/test" -driver=mysql
2023/02/19 11:13:52.313 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 11:13:52 INFO ▶ 0001 Using 'mysql' as 'driver'
2023/02/19 11:13:52 INFO ▶ 0002 Using '/home/zhangshixing/go_work_space/src/beeuse/migrateproject/database/migrations' as 'dir'
2023/02/19 11:13:52 INFO ▶ 0003 Running all outstanding migrations
2023/02/19 11:13:52 ERROR ▶ 0004 Could not build migration binary: exit status 1
2023/02/19 11:13:52 ERROR ▶ 0005 |> go: updates to go.mod needed; to update it:
2023/02/19 11:13:52 ERROR ▶ 0006 |> go mod tidy
2023/02/19 11:13:52 WARN ▶ 0007 Could not remove temporary file: remove m: no such file or directory
这里使用的模块github.com/astaxie/beego@latest found (v1.12.3)
。
从网上查询到的解决方法:
go get -u github.com/astaxie/beego@develop
go get -u github.com/beego/bee@v1.12.3
Beego需要恢复到1.x
版本,这里使用的是2.x
版本,不想使用1.x
所以找了另一种解决方法,具体看第4步。
上面的命令执行完成之后会生成migrations
表:
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| migrations |
| shop |
| user |
+----------------+
3 rows in set (0.00 sec)
4、人工migrate
在和20230219_105503_Student.go
同目录,也就是database/migrations/
目录下新建migrations.go
文
件,并将20230219_105503_Student.go
文件中的内容添加到migrations.go
文件中:
package mainimport ("flag""github.com/astaxie/beego/migration""github.com/astaxie/beego/orm"_ "github.com/go-sql-driver/mysql"_ "github.com/lib/pq""log""os"
)// DO NOT MODIFY
type Student_20230219_105503 struct {migration.Migration
}// DO NOT MODIFY
func init() {m := &Student_20230219_105503{}m.Created = "20230219_105503"migration.Register("Student_20230219_105503", m)
}// Run the migrations
func (m *Student_20230219_105503) Up() {// use m.SQL("CREATE TABLE ...") to make schema updatem.CreateTable("Student", "innodb", "utf8mb4")m.PriCol("id").SetAuto(true).SetDataType("int(11)").SetUnsigned(true)m.NewCol("nickname").SetDataType("varchar(255)").SetNullable(false)m.NewCol("avatar").SetDataType("varchar(32)").SetDefault("''").SetNullable(false)m.NewCol("status").SetDataType("tinyint(1)").SetUnsigned(true).SetDefault("1").SetNullable(false)m.NewCol("created_at").SetDataType("timestamp").SetDefault("NOW()").SetNullable(false)m.SQL(m.GetSQL())
}// Reverse the migrations
func (m *Student_20230219_105503) Down() {// use m.SQL("DROP TABLE ...") to reverse schema updatem.SQL("DROP TABLE IF EXISTS Student")
}var taskName stringfunc init() {flag.StringVar(&taskName, "task", "upgrade", "string flag value")
}func init() {orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/test")
}func main() {flag.Parse()task := taskNameswitch task {case "upgrade":if err := migration.Upgrade(0); err != nil {os.Exit(2)}log.Println("upgrade!")case "rollback":if err := migration.Rollback("Student_20230219_105503"); err != nil {os.Exit(2)}log.Println("rollback!")case "reset":if err := migration.Reset(); err != nil {os.Exit(2)}log.Println("reset!")case "refresh":if err := migration.Refresh(); err != nil {os.Exit(2)}log.Println("refresh!")}
}
注意 migration.Register("Student_20230219_105503", m)
和
migration.Rollback("Student_20230219_105503")
中Student_20230219_105503
要相互匹配。
运行前查询数据库:
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| shop |
| user |
+----------------+
2 rows in set (0.00 sec)
创建migrations
表:
CREATE TABLE `migrations` (`id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key',`name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique',`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back',`statements` longtext COMMENT 'SQL statements for this migration',`rollback_statements` longtext COMMENT 'SQL statment for rolling back migration',`status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back',PRIMARY KEY (`id_migration`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| migrations |
| shop |
| user |
+----------------+
3 rows in set (0.00 sec)mysql> select * from migrations;
Empty set (0.00 sec)
1.8.1 运行upgrade
[root@zsx migrations]# pwd
/home/zhangshixing/go_work_space/src/beeuse/migrateproject/database/migrations
[root@zsx migrations]# go run migrations.go -task upgrade
[ORM]2023/02/19 13:17:05 Detect DB timezone: +00:00:00.000000 parsing time "+00:00:00.000000": extra text: ".000000"
2023/02/19 13:17:05.445 [I] start upgrade Student_20230219_105503
2023/02/19 13:17:05.445 [I] exec sql: CREATE TABLE `Student` (`id` int(11) UNSIGNED auto_increment ,`nickname` varchar(255) NOT NULL ,`avatar` varchar(32) NOT NULL DEFAULT '',`status` tinyint(1) UNSIGNED NOT NULL DEFAULT 1,`created_at` timestamp NOT NULL DEFAULT NOW(),PRIMARY KEY( `id`))ENGINE=innodb DEFAULT CHARSET=utf8mb4;
2023/02/19 13:17:05.449 [I] end upgrade: Student_20230219_105503
2023/02/19 13:17:05.449 [I] total success upgrade: 1 migration
2023/02/19 13:17:07 upgrade!
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| Student |
| migrations |
| shop |
| user |
+----------------+
4 rows in set (0.00 sec)mysql> select * from migrations \G;
*************************** 1. row ***************************id_migration: 1name: Student_20230219_105503created_at: 2023-02-19 13:17:05statements: CREATE TABLE `Student` (`id` int(11) UNSIGNED auto_increment ,`nickname` varchar(255) NOT NULL ,`avatar` varchar(32) NOT NULL DEFAULT '',`status` tinyint(1) UNSIGNED NOT NULL DEFAULT 1,`created_at` timestamp NOT NULL DEFAULT NOW(),PRIMARY KEY( `id`))ENGINE=innodb DEFAULT CHARSET=utf8mb4;
rollback_statements: NULLstatus: update
1 row in set (0.00 sec)
upgrade
会执行建表,并且migrations.status
为update
。
根据需要的migrate
模式,修改task为upgrade
,rollback
,rest
和refresh
。
1.8.2 运行refresh
[root@zsx migrations]# go run migrations.go -task refresh
[ORM]2023/02/19 13:23:01 Detect DB timezone: +00:00:00.000000 parsing time "+00:00:00.000000": extra text: ".000000"
2023/02/19 13:23:01.042 [I] start reset: Student_20230219_105503
2023/02/19 13:23:01.042 [I] exec sql: DROP TABLE IF EXISTS Student
2023/02/19 13:23:01.046 [I] end reset: Student_20230219_105503
2023/02/19 13:23:01.046 [I] total success reset: 1 migration
2023/02/19 13:23:03.050 [I] total success upgrade: 0 migration
2023/02/19 13:23:05 refresh!
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| migrations |
| shop |
| user |
+----------------+
3 rows in set (0.00 sec)
mysql> select * from migrations \G;
*************************** 1. row ***************************id_migration: 1name: Student_20230219_105503created_at: 2023-02-19 13:23:01statements: CREATE TABLE `Student` (`id` int(11) UNSIGNED auto_increment ,`nickname` varchar(255) NOT NULL ,`avatar` varchar(32) NOT NULL DEFAULT '',`status` tinyint(1) UNSIGNED NOT NULL DEFAULT 1,`created_at` timestamp NOT NULL DEFAULT NOW(),PRIMARY KEY( `id`))ENGINE=innodb DEFAULT CHARSET=utf8mb4;
rollback_statements: DROP TABLE IF EXISTS Studentstatus: rollback
1 row in set (0.00 sec)
refresh
会执行删除表语句,并且migrations.status
为rollback
。
1.8.3 运行rollback
[root@zsx migrations]# go run migrations.go -task rollback
[ORM]2023/02/19 13:24:22 Detect DB timezone: +00:00:00.000000 parsing time "+00:00:00.000000": extra text: ".000000"
2023/02/19 13:24:22.194 [I] start rollback
2023/02/19 13:24:22.194 [I] exec sql: DROP TABLE IF EXISTS Student
2023/02/19 13:24:22.196 [I] end rollback
2023/02/19 13:24:24 rollback!
1.8.4 运行rest
[root@zsx migrations]# go run migrations.go -task rest
[ORM]2023/02/19 13:30:53 Detect DB timezone: +00:00:00.000000 parsing time "+00:00:00.000000": extra text: ".000000"
1.9 dockerize命令
这个命令可以通过生成 Dockerfile
文件来实现 docker 化你的应用。
例如生成一个以 1.6.4
版本Go环境为基础镜像的Dockerfile
,并暴露9000
端口。
[root@zsx beeuse]# bee dockerize -image="library/golang:1.6.4" -expose=9000
2023/02/19 13:39:06.183 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 13:39:06 INFO ▶ 0001 Generating Dockerfile...
2023/02/19 13:39:06 SUCCESS ▶ 0002 Dockerfile generated.
[root@zsx beeuse]# cat Dockerfile
FROM library/golang:1.6.4# Godep for vendoring
RUN go get github.com/tools/godep# Recompile the standard library without CGO
RUN CGO_ENABLED=0 go install -a stdENV APP_DIR $GOPATH/src/beeuse
RUN mkdir -p $APP_DIR# Set the entrypoint
ENTRYPOINT (cd $APP_DIR && ./beeuse)
ADD . $APP_DIR# Compile the binary and statically link
RUN cd $APP_DIR && CGO_ENABLED=0 godep go build -ldflags '-d -w -s'EXPOSE 9000
更多帮助信息可执行bee help dockerize
。
[root@zsx beeuse]# bee help dockerize
2023/02/19 13:39:43.344 [D] init global config instance failed. If you do not use this, just ignore it. open conf/app.conf: no such file or directory
USAGEbee dockerizeOPTIONS-expose=8080Port(s) to expose in the Docker container.-image=library/golangSet the base image of the Docker container.DESCRIPTIONDockerize generates a Dockerfile for your Beego Web Application.The Dockerfile will compile, get the dependencies with godep, and set the entrypoint.Example:$ bee dockerize -expose="3000,80,25"
在hello
项目下执行:
[root@zsx hello]# bee dockerize -expose="8080"
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 13:41:49 INFO ▶ 0001 Generating Dockerfile...
2023/02/19 13:41:49 SUCCESS ▶ 0002 Dockerfile generated.
[root@zsx hello]# cat Dockerfile
FROM library/golang# Godep for vendoring
RUN go get github.com/tools/godep# Recompile the standard library without CGO
RUN CGO_ENABLED=0 go install -a stdENV APP_DIR $GOPATH/src/beeuse/hello
RUN mkdir -p $APP_DIR# Set the entrypoint
ENTRYPOINT (cd $APP_DIR && ./hello)
ADD . $APP_DIR# Compile the binary and statically link
RUN cd $APP_DIR && CGO_ENABLED=0 godep go build -ldflags '-d -w -s'EXPOSE 8080
1.10 bee 工具配置文件
你可能已经注意到,在 bee 工具的源码目录下有一个 bee.json
文件,这个文件是针对 bee 工具的一些行为进行
配置。该功能还未完全开发完成,不过其中的一些选项已经可以使用:
-
"version": 0
:配置文件版本,用于对比是否发生不兼容的配置格式版本。 -
"go_install": false
:如果你的包均使用完整的导入路径(例如:github.com/user/repo/subpkg
),则可以启用该选项来进行
go install
操作,加快构建操作。 -
"watch_ext": []
:用于监控其它类型的文件(默认只监控后缀为.go
的文件)。 -
"dir_structure":{}
:如果你的目录名与默认的 MVC 架构的不同,则可以使用该选项进行修改。 -
"cmd_args": []
:如果你需要在每次启动时加入启动参数,则可以使用该选项。 -
"envs": []
:如果你需要在每次启动时设置临时环境变量参数,则可以使用该选项。