Beego之Bee工具使用

1、bee工具使用

bee 工具是一个为了协助快速开发 Beego 项目而创建的项目,通过 bee 你可以很容易的进行 Beego 项目的创

建、热编译、开发、测试、和部署。Bee工具可以使用的命令:

shell 复制代码
[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.0

USAGE
    bee command [arguments]

AVAILABLE COMMANDS

    version     Prints the current Bee version
    migrate     Runs database migrations
    api         Creates a Beego API application
    bale        Transforms non-Go files to Go source files
    fix         Fixes your application by making it compatible with newer versions of Beego
    pro         Source code generator
    dev         Commands which used to help to develop beego and bee
    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
    new         Creates a Beego application
    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
    update      Update Bee

Use bee help [command] for more information about a command.

ADDITIONAL HELP TOPICS


Use bee help [topic] for more information about that topic.

可以使用bee help 命令来查看某一个命令的具体使用方式。

1.1 new 命令

new 命令是新建一个 Web 项目,我们在命令行下执行 bee new <项目名> 就可以创建一个新的项目。但是注意该

命令必须在 $GOPATH/src 下执行,最后会在 $GOPATH/src 相应目录下生成项目结构。

该命令在上一篇我们已经演示过了。

shell 复制代码
# 帮助命令
[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
USAGE
  bee new [appname] [-gopath=false] [-beego=v1.12.3]

OPTIONS
  -beego
      set beego version,only take effect by go mod

  -gopath
      Support go path,default false

DESCRIPTION
  Creates a Beego application for the given app name in the current directory.
  now defaults to generating as a go modules project
  The 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 应用的,执行命令之后如下所示:

shell 复制代码
[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.mod
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/conf
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllers
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/tests
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/conf/app.conf
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/models
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/routers/
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllers/object.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/controllers/user.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/tests/default_test.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/routers/router.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/models/object.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/models/user.go
        create   /home/zhangshixing/go_work_space/src/beeuse/apiproject/main.go
2023/02/18 18:30:16 SUCCESS  ▶ 0003 New API successfully created!

这个项目的目录结构如下:

shell 复制代码
[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.go

5 directories, 9 files

从上面的目录我们可以看到和 Web 项目相比,少了 staticviews 目录,多了一个 test 模块,用来做单元

测试的。

shell 复制代码
# 帮助命令
[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
USAGE
  bee api [appname]

OPTIONS
  -beego
      set beego version,only take effect by go mod

  -conn
      Connection string used by the driver to connect to a database instance.

  -driver
      Database driver. Either mysql, postgres or sqlite.

  -gopath
      Support go path,default false

  -tables
      List of table names separated by a comma.

DESCRIPTION
  The 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 command
  will 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

同时,该命令还支持一些自定义参数自动连接数据库创建相关 modelcontroller

bee api [appname] [-tables=""] [-driver=mysql] [-conn="root:@tcp(127.0.0.1:3306)/test"]

如果conn参数为空则创建一个示例项目,否则将基于链接信息链接数据库创建项目。

shell 复制代码
[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.mod
        create   /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject
        create   /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/conf
        create   /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/controllers
        create   /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/tests
        create   /home/zhangshixing/go_work_space/src/beeuse/apidatabaseproject/conf/app.conf
        create   /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!

目录结构如下:

shell 复制代码
[root@zsx beeuse]# tree apidatabaseproject/
apidatabaseproject/
├── conf
│   └── app.conf
├── controllers
│   └── shop.go
├── go.mod
├── main.go
├── models
│   └── shop.go
├── routers
│   └── router.go
└── tests

5 directories, 6 files

1.3 run命令

我们在开发 Go 项目的时候最大的问题是经常需要自己手动去编译再运行,bee run 命令是监控 beego 的项目,

通过 [fsnotify] https://github.com/howeyc/fsnotify监控文件系统。但是注意该命令必须在

$GOPATH/src/appname 下执行。 这样我们在开发过程中就可以实时的看到项目修改之后的效果。

该命令在上一篇也已经演示过了。

shell 复制代码
# 帮助文档
[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
USAGE
  bee run [appname] [watchall] [-main=*.go] [-downdoc=true]  [-gendoc=true] [-vendor=true] [-e=folderToExclude] [-ex=extraPackageToWatch] [-tags=goBuildTags] [-runmode=BEEGO_RUNMODE]

OPTIONS
  -downdoc
      Enable auto-download of the swagger file if it does not exist.

  -e=[]
      List of paths to exclude.

  -ex=[]
      List of extra package to watch.

  -gendoc
      Enable auto-generate the docs.

  -ldflags
      Set the build ldflags. See: https://golang.org/pkg/go/build/

  -main=[]
      Specify main go files.

  -runargs
      Extra args to run application

  -runmode
      Set the Beego run mode.

  -tags
      Set the build tags. See: https://golang.org/pkg/go/build/

  -vendor=false
      Enable watch vendor folder.

DESCRIPTION
  Run command will supervise the filesystem of the application for any changes, and recompile/restart it.

1.4 pack命令

pack 目录用来发布应用的时候打包,会把项目打包成 zip 包,这样我们部署的时候直接把打包之后的项目上传,

解压就可以部署了。

shell 复制代码
[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!

我们可以看到目录下有如下的压缩文件:

shell 复制代码
[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
shell 复制代码
# 帮助文档
[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
USAGE
  bee pack

OPTIONS
  -a
      Set the application name. Defaults to the dir name.

  -b=true
      Tell the command to do a build for the current platform. Defaults to true.

  -ba
      Specify 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:.tmp
      Set suffixes of paths to be excluded. Uses a column (:) as separator.

  -f=tar.gz
      Set file format. Either tar.gz or zip. Defaults to tar.gz.

  -fs=false
      Tell the command to follow symlinks. Defaults to false.

  -o
      Set the compressed file output path. Defaults to the current path.

  -p
      Set the application path. Defaults to the current path.

  -ss=false
      Tell the command to skip symlinks. Defaults to false.

  -v=false
      Be more verbose during the operation. Defaults to false.

DESCRIPTION
  Pack 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命令

这个命令目前仅限内部使用,具体实现方案未完善,主要用来压缩所有的静态文件变成一个变量申明文件,全部编

译到二进制文件里面,用户发布的时候携带静态文件,包括 jscssimgviews。最后在启动运行时进行

非覆盖式的自解压。

shell 复制代码
[root@zsx hello]# bee bale
______
| ___ \
| |_/ /  ___   ___
| ___ \ / _ \ / _ \
| |_/ /|  __/|  __/
\____/  \___| \___| v2.0.4
2023/02/18 19:01:02 SUCCESS  ▶ 0001 Baled resources successfully!
shell 复制代码
[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
shell 复制代码
# 帮助文档
[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
USAGE
  bee bale

DESCRIPTION
  Bale 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 and
  views 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 的版本,这样一旦用户出现错误,可以通过该命令来查看当前的版本。

shell 复制代码
[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的版本信息。

shell 复制代码
# 帮助文档
[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
USAGE
  bee version

OPTIONS
  -o
      Set the output format. Either json or yaml.

DESCRIPTION
  Prints the current Bee, Beego and Go version alongside the platform information.

1.7 generate命令

这个命令是用来自动化的生成代码的,包含了从数据库一键生成 model,还包含了 scaffold 的,通过这个命令,

让大家开发代码不再慢。

shell 复制代码
# 帮助文档
[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
USAGE
  bee generate [command]

OPTIONS
  -conn
      Connection string used by the SQLDriver to connect to a database instance.

  -ctrlDir
      Controller directory. Bee scans this directory and its sub directory to generate routers

  -ddl
      Generate DDL Migration

  -driver
      Database SQLDriver. Either mysql, postgres or sqlite.

  -fields
      List of table Fields.

  -level
      Either 1, 2 or 3. i.e. 1=models; 2=models and controllers; 3=models, controllers and routers.

  -routersFile
      Routers file. If not found, Bee create a new one. Bee will truncates this file and output routers info into this file

  -routersPkg
      router's package. Default is routers, it means that "package routers" in the generated file

  -tables
      List 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
shell 复制代码
▶ 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)/test
    example: bee generate scaffold post -fields="title:string,body:text"

第一步创建表:

sql 复制代码
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自动生成代码:

shell 复制代码
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:连接信息

shell 复制代码
[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 name
        create   /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.tpl
        create   /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/show.tpl
        create   /home/zhangshixing/go_work_space/src/beeuse/scaffoldproject/views/user/create.tpl
        create   /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.go

2023/02/18 19:14:30 SUCCESS  ▶ 0013 Scaffold successfully generated!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree scaffoldproject/
scaffoldproject/
├── controllers
│   └── user.go
├── models
│   └── user.go
└── views
    └── user
        ├── create.tpl
        ├── edit.tpl
        ├── index.tpl
        └── show.tpl

4 directories, 6 files

第三步执行命令:

shell 复制代码
[root@zsx scaffoldproject]# go mod init
[root@zsx scaffoldproject]# go mod tidy
1.7.2 generate model
shell 复制代码
▶ 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, ...
shell 复制代码
# 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 name
        create   /home/zhangshixing/go_work_space/src/beeuse/modelproject/models/user.go
2023/02/18 19:19:15 SUCCESS  ▶ 0003 Model successfully generated!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree modelproject/
modelproject/
└── models
    └── user.go

1 directory, 1 file
1.7.3 generate controller
shell 复制代码
▶ To generate a controller:

     $ bee generate controller [controllerfile]
     generate RESTful controllers
shell 复制代码
[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 name
        create   /home/zhangshixing/go_work_space/src/beeuse/controllerproject/controllers/usercontroller.go
2023/02/18 20:09:26 SUCCESS  ▶ 0003 Controller successfully generated!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree controllerproject/
controllerproject/
└── controllers
    └── usercontroller.go

1 directory, 1 file
1.7.4 generate view
shell 复制代码
▶ To generate a CRUD view:

     $ bee generate view [viewpath]
     generate CRUD view in viewpath
shell 复制代码
[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.tpl
        create   /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/show.tpl
        create   /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/create.tpl
        create   /home/zhangshixing/go_work_space/src/beeuse/viewproject/views/UserView/edit.tpl
2023/02/18 20:11:43 SUCCESS  ▶ 0002 View successfully generated!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree viewproject/
viewproject/
└── views
    └── UserView
        ├── create.tpl
        ├── edit.tpl
        ├── index.tpl
        └── show.tpl

2 directories, 4 files
1.7.5 generate migration
shell 复制代码
▶ 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, ...
shell 复制代码
[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 name
        create   /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!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree migrationproject/
migrationproject/
└── database
    └── migrations
        └── 20230218_201947_User.go

2 directories, 1 file
1.7.6 generate routers

generate routers 是从原来beego中剥离出来的功能。在早期,beego的项目必须在启动的时候才会触发生成

路由文件。

现在我们把这个东西挪了出来,那么用户可以有更好的控制感。

shell 复制代码
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、新建一个项目

shell 复制代码
[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.mod
        create   /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.conf
        create   /home/zhangshixing/go_work_space/src/swaggerdemo/controllers/default.go
        create   /home/zhangshixing/go_work_space/src/swaggerdemo/views/index.tpl
        create   /home/zhangshixing/go_work_space/src/swaggerdemo/routers/router.go
        create   /home/zhangshixing/go_work_space/src/swaggerdemo/tests/default_test.go
        create   /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

go 复制代码
package controllers

import (
	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

go 复制代码
package routers

import (
	"swaggerdemo/controllers"
	beego "github.com/beego/beego/v2/server/web"
)

func init() {
  beego.Include(&controllers.MainController{})
}

4、生成routers

默认项目会自动生成/routers/commentsRouter_controllers.go,这里也可以自己生成。

shell 复制代码
[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!
shell 复制代码
[root@zsx swaggerdemo]# ls routers/
commentsRouter_controllers.go  commentsRouter.go  router.go

也可以指定自己生成的地方:

shell 复制代码
[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
shell 复制代码
▶ 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

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 routers

import (
	"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注释:

go 复制代码
package controllers

import (
	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、生成

shell 复制代码
[root@zsx swaggerdemo]# bee generate docs
______
| ___ \
| |_/ /  ___   ___
| ___ \ / _ \ / _ \
| |_/ /|  __/|  __/
\____/  \___| \___| v2.0.4
2023/02/18 22:16:23 SUCCESS  ▶ 0001 Docs successfully generated!
shell 复制代码
[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是新生成的目录,内容如下:

shell 复制代码
[root@zsx swaggerdemo]# ls swagger
swagger.json  swagger.yml

查看swagger.json文件的内容:

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

shell 复制代码
[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 changed

2023/02/18 22:17:27.026 [I] [server.go:241]  http server Running on http://:8080

swagger目录下新生成了许多文件:

shell 复制代码
[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文件:

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 system
    const 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、重新启动项目

shell 复制代码
[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 comments

2023/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

整个项目的结构:

shell 复制代码
[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.tpl

11 directories, 27 files
1.7.8 generate test
shell 复制代码
▶ To generate a test case:

     $ bee generate test [routerfile]
     generate testcase

该命令在高版本中已经被移除。

shell 复制代码
[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
shell 复制代码
▶ 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)/test
             default for postgres: postgres://postgres:postgres@127.0.0.1:5432/postgres
    -level:  [1 | 2 | 3], 1 = models; 2 = models,controllers; 3 = models,controllers,router
shell 复制代码
[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!

生成的目录结构:

shell 复制代码
[root@zsx beeuse]# tree appcodeproject/
appcodeproject/
├── controllers
│   └── user.go
├── models
│   └── user.go
└── routers
    └── router.go

3 directories, 3 files

1.8 migrate命令

这个命令是应用的数据库迁移命令,主要是用来每次应用升级,降级的SQL管理。

shell 复制代码
# 帮助文档
[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
USAGE
  bee migrate [Command]

OPTIONS
  -conn
      Connection string used by the driver to connect to a database instance.

  -dir
      The directory where the migration files are stored

  -driver
      Database driver. Either mysql, postgres or sqlite.

DESCRIPTION
  The 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"]

命令参数:

shell 复制代码
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)/test

bee 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)/test

bee 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)/test

bee 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、生成迁移文件

shell 复制代码
[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 name
        create   /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、完成迁移脚本

shell 复制代码
[root@zsx migrateproject]# ls database/migrations/
20230219_105503_Student.go
[root@zsx migrateproject]# vim database/migrations/20230219_105503_Student.go
go 复制代码
package main

import (
	"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 update
	m.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 update
	m.SQL("DROP TABLE IF EXISTS Student")
}

此处注意默认空字符的写法,SetDefault("''")

3、执行迁移命令

shell 复制代码
[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)

从网上查询到的解决方法:

shell 复制代码
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表:

sql 复制代码
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文件中:

go 复制代码
package main

import (
	"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 update
	m.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 update
	m.SQL("DROP TABLE IF EXISTS Student")
}

var taskName string

func 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 := taskName
	switch 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要相互匹配。

运行前查询数据库:

sql 复制代码
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| shop           |
| user           |
+----------------+
2 rows in set (0.00 sec)

创建migrations表:

sql 复制代码
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;
sql 复制代码
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
shell 复制代码
[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!
sql 复制代码
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: 1
               name: Student_20230219_105503
         created_at: 2023-02-19 13:17:05
         statements: 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: NULL
             status: update
1 row in set (0.00 sec)

upgrade会执行建表,并且migrations.statusupdate

根据需要的migrate模式,修改task为upgraderollbackrestrefresh

1.8.2 运行refresh
shell 复制代码
[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!
sql 复制代码
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| migrations     |
| shop           |
| user           |
+----------------+
3 rows in set (0.00 sec)
sql 复制代码
mysql> select * from migrations \G;
*************************** 1. row ***************************
       id_migration: 1
               name: Student_20230219_105503
         created_at: 2023-02-19 13:23:01
         statements: 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 Student
             status: rollback
1 row in set (0.00 sec)

refresh会执行删除表语句,并且migrations.statusrollback

1.8.3 运行rollback
sql 复制代码
[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
shell 复制代码
[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端口。

shell 复制代码
[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.
shell 复制代码
[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 std

ENV 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

shell 复制代码
[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
USAGE
  bee dockerize

OPTIONS
  -expose=8080
      Port(s) to expose in the Docker container.

  -image=library/golang
      Set the base image of the Docker container.

DESCRIPTION
  Dockerize 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项目下执行:

shell 复制代码
[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.
shell 复制代码
[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 std

ENV 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": []:如果你需要在每次启动时设置临时环境变量参数,则可以使用该选项。

相关推荐
小石潭记丶8 天前
Windows如何安装go环境,离线安装beego
go·beego
GoppViper3 个月前
golang学习笔记32——golang Beego 框架使用详解
笔记·后端·学习·golang·go·beego
汪碧康7 个月前
【k8s多集群管理平台开发实践】八、client-go实现service读取列表、创建service、读取yaml配置并更新
golang·kubernetes·layui·beego
汪碧康7 个月前
【k8s多集群管理平台开发实践】十一、client-go实现读取k8s的事件信息
golang·kubernetes·layui·beego
witton7 个月前
使用Beego创建API项目并自动化文档
自动化·api·swagger·fetch·beego·cors·bee
汪碧康8 个月前
【k8s多集群管理平台开发实践】七、clint-go实现configmap的列表、创建configmap、yaml配置的编辑
容器·golang·kubernetes·layui·beego
汪碧康8 个月前
【k8s多集群管理平台开发实践】六、client-go实现k8s的cronjob的列表、创建cronjob、yaml配置更新
容器·golang·kubernetes·layui·beego
闫铁娃8 个月前
Go实战训练之Web Server 与路由树
前端·后端·中间件·golang·gin·beego
程序猿代码之路8 个月前
Beego框架学习
beego
是阿尘呀8 个月前
Go Web框架-Beego
开发语言·前端·后端·golang·beego