做违法网站判刑吗,网页制作学什么软件好,快速开发平台破解版,做购物商城类网站需要1、bee工具使用
bee 工具是一个为了协助快速开发 Beego 项目而创建的项目#xff0c;通过 bee 你可以很容易的进行 Beego 项目的创
建、热编译、开发、测试、和部署。Bee工具可以使用的命令#xff1a;
[rootzsx ~]# bee
2023/02/18 18:17:26.196 [D] init global config…1、bee工具使用
bee 工具是一个为了协助快速开发 Beego 项目而创建的项目通过 bee 你可以很容易的进行 Beego 项目的创
建、热编译、开发、测试、和部署。Bee工具可以使用的命令
[rootzsx ~]# 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 相应目录下生成项目结构。
该命令在上一篇我们已经演示过了。
# 帮助命令
[rootzsx 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] [-gopathfalse] [-beegov1.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] [-gopathfalse] [-beegov1.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.tpl1.2 api命令
上面的 new 命令是用来新建 Web 项目不过很多用户使用 beego 来开发 API 应用。所以这个 api 命令就是用
来创建 API 应用的执行命令之后如下所示
[rootzsx 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!这个项目的目录结构如下
[rootzsx 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 模块用来做单元
测试的。
# 帮助命令
[rootzsx 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] [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-gopathfalse] [-beegov1.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] [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test]
如果conn参数为空则创建一个示例项目否则将基于链接信息链接数据库创建项目。
[rootzsx beeuse]# bee api apidatabaseproject -tablesshop -drivermysql -connroot:roottcp(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:roottcp(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!目录结构如下
[rootzsx beeuse]# tree apidatabaseproject/
apidatabaseproject/
├── conf
│ └── app.conf
├── controllers
│ └── shop.go
├── go.mod
├── main.go
├── models
│ └── shop.go
├── routers
│ └── router.go
└── tests5 directories, 6 files1.3 run命令
我们在开发 Go 项目的时候最大的问题是经常需要自己手动去编译再运行bee run 命令是监控 beego 的项目
通过 [fsnotify] https://github.com/howeyc/fsnotify监控文件系统。但是注意该命令必须在
$GOPATH/src/appname 下执行。 这样我们在开发过程中就可以实时的看到项目修改之后的效果。
该命令在上一篇也已经演示过了。
# 帮助文档
[rootzsx 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] [-downdoctrue] [-gendoctrue] [-vendortrue] [-efolderToExclude] [-exextraPackageToWatch] [-tagsgoBuildTags] [-runmodeBEEGO_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/-vendorfalseEnable watch vendor folder.DESCRIPTIONRun command will supervise the filesystem of the application for any changes, and recompile/restart it.1.4 pack命令
pack 目录用来发布应用的时候打包会把项目打包成 zip 包这样我们部署的时候直接把打包之后的项目上传
解压就可以部署了。
[rootzsx 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: GOOSlinux GOARCHamd64
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!我们可以看到目录下有如下的压缩文件
[rootzsx 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# 帮助文档
[rootzsx 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.-btrueTell 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. GOARCHarm.-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.-ftar.gzSet file format. Either tar.gz or zip. Defaults to tar.gz.-fsfalseTell 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.-ssfalseTell the command to skip symlinks. Defaults to false.-vfalseBe 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 -w1.5 bale命令
这个命令目前仅限内部使用具体实现方案未完善主要用来压缩所有的静态文件变成一个变量申明文件全部编
译到二进制文件里面用户发布的时候携带静态文件包括 js、css、img 和 views。最后在启动运行时进行
非覆盖式的自解压。
[rootzsx hello]# bee bale
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 19:01:02 SUCCESS ▶ 0001 Baled resources successfully![rootzsx 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# 帮助文档
[rootzsx 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 的版本这样一旦用户出现错误可以通过该命令来查看当前的版本。
[rootzsx 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的版本信息。
# 帮助文档
[rootzsx 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 的通过这个命令
让大家开发代码不再慢。
# 帮助文档
[rootzsx 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. 1models; 2models and controllers; 3models, 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-routersPkgrouters 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] [-fieldstitle:string,body:text] [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test]▶ To generate a Model based on fields:$ bee generate model [modelname] [-fieldsname: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] [-fieldsname: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] [-routersPkgmyPackage]▶ To generate a test case:$ bee generate test [routerfile]▶ To generate appcode based on an existing database:$ bee generate appcode [-tables] [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-level3]1.7.1 generate scaffold
▶ To scaffold out your entire application:$ bee generate scaffold [scaffoldname] [-fieldstitle:string,body:text] [-drivermysql] [-connroot: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 -fieldstitle: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 -fieldsid:int64,name:string,gender:int,age:int -drivermysql -connroot:roottcp(127.0.0.1:3306)/test说明 scaffold脚手架 user是表名 -fields是表字段名字段名冒号类型逗号 -driver驱动类型 -conn连接信息
[rootzsx beeuse]# mkdir scaffoldproject
[rootzsx beeuse]# cd scaffoldproject/
[rootzsx scaffoldproject]# bee generate scaffold user -fieldsid:int64,name:string,gender:int,age:int -drivermysql -connroot:roottcp(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 Usercreate /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! Dont forget to add beego.Router(/user ,controllers.UserController{}) to routers/route.go2023/02/18 19:14:30 SUCCESS ▶ 0013 Scaffold successfully generated!生成的目录结构
[rootzsx beeuse]# tree scaffoldproject/
scaffoldproject/
├── controllers
│ └── user.go
├── models
│ └── user.go
└── views└── user├── create.tpl├── edit.tpl├── index.tpl└── show.tpl4 directories, 6 files第三步执行命令
[rootzsx scaffoldproject]# go mod init
[rootzsx scaffoldproject]# go mod tidy1.7.2 generate model
▶ To generate a Model based on fields:$ bee generate model [modelname] [-fieldsname:type]generate RESTful model based on fields-fields: a list of table fields. Format: field:type, ...# User是实体类的名字
[rootzsx beeuse]# mkdir modelproject
[rootzsx beeuse]# cd modelproject/
[rootzsx modelproject]# bee generate model User -fieldsid: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!生成的目录结构
[rootzsx beeuse]# tree modelproject/
modelproject/
└── models└── user.go1 directory, 1 file1.7.3 generate controller
▶ To generate a controller:$ bee generate controller [controllerfile]generate RESTful controllers[rootzsx beeuse]# mkdir controllerproject
[rootzsx beeuse]# cd controllerproject/
[rootzsx 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!生成的目录结构
[rootzsx beeuse]# tree controllerproject/
controllerproject/
└── controllers└── usercontroller.go1 directory, 1 file1.7.4 generate view
▶ To generate a CRUD view:$ bee generate view [viewpath]generate CRUD view in viewpath[rootzsx beeuse]# mkdir viewproject
[rootzsx beeuse]# cd viewproject/
[rootzsx 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!生成的目录结构
[rootzsx beeuse]# tree viewproject/
viewproject/
└── views└── UserView├── create.tpl├── edit.tpl├── index.tpl└── show.tpl2 directories, 4 files1.7.5 generate migration
▶ To generate a migration file for making database schema updates:$ bee generate migration [migrationfile] [-fieldsname:type]generate migration file for making database schema update-fields: a list of table fields. Format: field:type, ...[rootzsx beeuse]# mkdir migrationproject
[rootzsx beeuse]# cd migrationproject/
[rootzsx 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!生成的目录结构
[rootzsx beeuse]# tree migrationproject/
migrationproject/
└── database└── migrations└── 20230218_201947_User.go2 directories, 1 file1.7.6 generate routers
generate routers 是从原来beego中剥离出来的功能。在早期beego的项目必须在启动的时候才会触发生成
路由文件。
现在我们把这个东西挪了出来那么用户可以有更好的控制感。
bee generate routers [-ctrlDir/path/to/controller/directory] [-routersFile/path/to/routers/file.go] [-routersPkgmyPackage]-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 parameter1、新建一个项目
[rootzsx 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![rootzsx swaggerdemo]# go mod tidy2、修改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/controllersbeego github.com/beego/beego/v2/server/web
)func init() {beego.Include(controllers.MainController{})
}4、生成routers
默认项目会自动生成/routers/commentsRouter_controllers.go这里也可以自己生成。
[rootzsx 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 files package
2023/02/18 22:11:34 SUCCESS ▶ 0004 Routers successfully generated![rootzsx swaggerdemo]# ls routers/
commentsRouter_controllers.go commentsRouter.go router.go也可以指定自己生成的地方
[rootzsx beeuse]# mkdir routersproject
[rootzsx beeuse]# cd routersproject/
[rootzsx routersproject]# bee generate routers -ctrlDir/home/zhangshixing/go_work_space/src/swaggerdemo/controllers/ -routersFile$GOPATH/src/beeuse/routersproject//routercomments.go -routersPkgmypackage
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 -routersPkgmypackage]
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 files package
2023/02/18 22:13:46 SUCCESS ▶ 0004 Routers successfully generated!
[rootzsx routersproject]# ll
total 4
-rw-r--r--. 1 root root 1336 Feb 18 22:13 routercomments.go1.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] [-routersPkgmyPackage]在上一小节的项目的基础上进行修改。
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 qingyuegmail.com
// TermsOfServiceUrl http://beego.me/
// License Apache 2.0
// LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
package routersimport (swaggerdemo/controllersbeego 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、生成
[rootzsx swaggerdemo]# bee generate docs
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/18 22:16:23 SUCCESS ▶ 0001 Docs successfully generated![rootzsx 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 viewsswagger是新生成的目录内容如下
[rootzsx 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: qingyuegmail.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
[rootzsx swaggerdemo]# bee run -gendoctrue -downdoctrue
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| 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://:8080swagger目录下新生成了许多文件
[rootzsx 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.js6、停掉项目修改swagger/index.html文件
script src./swagger-ui-bundle.js charsetUTF-8 /script
script src./swagger-ui-standalone-preset.js charsetUTF-8 /script
scriptwindow.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}
/script7、重新启动项目
[rootzsx swaggerdemo]# bee run -gendoctrue -downdoctrue
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| 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://:80808、访问路径http://127.0.0.1:8080/swagger/ 访问v1/main/none 访问v1/main/all:key 整个项目的结构
[rootzsx 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 files1.7.8 generate test
▶ To generate a test case:$ bee generate test [routerfile]generate testcase该命令在高版本中已经被移除。
[rootzsx beeuse]# mkdir testproject
[rootzsx beeuse]# cd testproject/
[rootzsx 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 missing1.7.9 generate appcode
▶ To generate appcode based on an existing database:$ bee generate appcode [-tables] [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-level3]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:postgres127.0.0.1:5432/postgres-level: [1 | 2 | 3], 1 models; 2 models,controllers; 3 models,controllers,router[rootzsx beeuse]# mkdir appcodeproject
[rootzsx beeuse]# cd appcodeproject/
[rootzsx appcodeproject]# bee generate appcode -tablesuser -drivermysql -connroot:roottcp(127.0.0.1:3306)/test -level3
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:roottcp(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!生成的目录结构
[rootzsx beeuse]# tree appcodeproject/
appcodeproject/
├── controllers
│ └── user.go
├── models
│ └── user.go
└── routers└── router.go3 directories, 3 files1.8 migrate命令
这个命令是应用的数据库迁移命令主要是用来每次应用升级降级的SQL管理。
# 帮助文档
[rootzsx 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 [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-dirpath/to/migration]▶ To rollback the last migration:$ bee migrate rollback [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-dirpath/to/migration]▶ To do a reset, which will rollback all the migrations:$ bee migrate reset [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-dirpath/to/migration]▶ To update your schema:$ bee migrate refresh [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-dirpath/to/migration]命令参数
bee migrate [-drivermysql] [-connroot: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 [-drivermysql] [-connroot: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 [-drivermysql] [-connroot: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 [-drivermysql] [-connroot: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、生成迁移文件
[rootzsx beeuse]# mkdir migrateproject
[rootzsx beeuse]# cd migrateproject/
# 命令格式
# bee generate migration [migrationfile] [-fieldsname:type]
[rootzsx 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、完成迁移脚本
[rootzsx migrateproject]# ls database/migrations/
20230219_105503_Student.go
[rootzsx migrateproject]# vim database/migrations/20230219_105503_Student.gopackage mainimport (fmtgithub.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_105503migration.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、执行迁移命令
[rootzsx migrateproject]# go mod init
[rootzsx migrateproject]# go mod tidy
# 命令格式
# bee migrate [-drivermysql] [-connroot:tcp(127.0.0.1:3306)/test] [-dirpath/to/migration]
[rootzsx migrateproject]# bee migrate -connroot:roottcp(127.0.0.1:3306)/test -drivermysql
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/beegolatest found (v1.12.3)。
从网上查询到的解决方法
go get -u github.com/astaxie/beegodevelop
go get -u github.com/beego/beev1.12.3Beego需要恢复到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 (flaggithub.com/astaxie/beego/migrationgithub.com/astaxie/beego/orm_ github.com/go-sql-driver/mysql_ github.com/lib/pqlogos
)// DO NOT MODIFY
type Student_20230219_105503 struct {migration.Migration
}// DO NOT MODIFY
func init() {m : Student_20230219_105503{}m.Created 20230219_105503migration.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:roottcp(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)
) ENGINEInnoDB DEFAULT CHARSETutf8;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
[rootzsx migrations]# pwd
/home/zhangshixing/go_work_space/src/beeuse/migrateproject/database/migrations
[rootzsx 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))ENGINEinnodb DEFAULT CHARSETutf8mb4;
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))ENGINEinnodb DEFAULT CHARSETutf8mb4;
rollback_statements: NULLstatus: update
1 row in set (0.00 sec)upgrade会执行建表并且migrations.status为update。
根据需要的migrate模式修改task为upgraderollbackrest和refresh。
1.8.2 运行refresh
[rootzsx 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))ENGINEinnodb DEFAULT CHARSETutf8mb4;
rollback_statements: DROP TABLE IF EXISTS Studentstatus: rollback
1 row in set (0.00 sec)refresh会执行删除表语句并且migrations.status为rollback。
1.8.3 运行rollback
[rootzsx 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
[rootzsx 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: .0000001.9 dockerize命令
这个命令可以通过生成 Dockerfile 文件来实现 docker 化你的应用。
例如生成一个以 1.6.4 版本Go环境为基础镜像的Dockerfile并暴露9000端口。
[rootzsx beeuse]# bee dockerize -imagelibrary/golang:1.6.4 -expose9000
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.[rootzsx 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_ENABLED0 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_ENABLED0 godep go build -ldflags -d -w -sEXPOSE 9000更多帮助信息可执行bee help dockerize。
[rootzsx 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-expose8080Port(s) to expose in the Docker container.-imagelibrary/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 -expose3000,80,25在hello项目下执行
[rootzsx hello]# bee dockerize -expose8080
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.4
2023/02/19 13:41:49 INFO ▶ 0001 Generating Dockerfile...
2023/02/19 13:41:49 SUCCESS ▶ 0002 Dockerfile generated.[rootzsx hello]# cat Dockerfile
FROM library/golang# Godep for vendoring
RUN go get github.com/tools/godep# Recompile the standard library without CGO
RUN CGO_ENABLED0 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_ENABLED0 godep go build -ldflags -d -w -sEXPOSE 80801.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: []如果你需要在每次启动时设置临时环境变量参数则可以使用该选项。