Premise work
Building environment, can refer to the following two tutorial:
building an environment in Go
structures Go locale 2
Installation beego
beego typical form of installation is installation package Go:
go get github.com/astaxie/beego
common problem:
- git https unable to obtain, configure local git, close https verification:
git config --global http.sslVerify false
- If, because of network problems can not download, please refer to the following
源码下载升级
way
beego go into upgrade mode and upgrade source download upgrades:
- Go upgrade, you can upgrade beego frame this way the user is strongly recommended in this way:
go get -u github.com/astaxie/beego
- Source download the upgrade, users access https://github.com/astaxie/beego , download the source code, then cover GOPATH $ / src / github.com/astaxie/beego directory and then executed locally by the installation can be upgraded:
go install github.com/astaxie/beego
Installation bee Tool
bee tool is a project to assist in the rapid development beego project created, you can easily be created by the project beego bee, hot compile, develop, test, and deployment.
Bee installation tool by way:
go get github.com/beego/bee
After installing, bee executable files by default stored in $GOPATH/bin
there, so you need to $GOPATH/bin
add to your environment variables can only be the next step.
At the command line bee
, the following message appears if the installation was successful
We can GOPATH/bin
find directory generated bee.exe
executable file as follows:
New beego web project
new
Command is to create a Web project in the command input bee new <项目名>
, such as we enter the command bee new myapp
, the results are as follows:
bee tool will automatically $GOPATH/src
generate myapp project directory, as follows:
Startup project
命令窗口定位到myapp目录下,运行命令bee run
即可启动项目
启动成功,红框部分显示项目运行端口为8080,我们通过浏览器访问:localhost:8080,即可进入如下界面
写一个hello world
用idea打开该项目,下面是整体的项目结构
在controllers目录下新建hello.go文件,内容如下:
package controllers
import (
"github.com/astaxie/beego" ) type HelloController struct { beego.Controller //这里相当于继承beego.Controller } //重写Get方法 func (hello *HelloController) Get() { hello.Ctx.WriteString("hello go") }
上面的代码显示首先我们声明了一个控制器 HelloController
,这个控制器里面内嵌了beego.Controller
,这就是 Go 的嵌入方式,也就是HelloController
自动拥有了所有 beego.Controller 的方法。这类似于面向对象里的继承。
而beego.Controller
拥有很多方法,其中包括Init、Prepare、Post、Get、Delete、Head
等方法。我们可以通过重写的方式来实现这些方法,而我们上面的代码就是重写了Get
方法。
然后将新增的HelloController
添加路由,修改routers/router.go文件,如下:
package routers
import (
"myapp/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) // 新增路由 beego.Router("/hello", &controllers.HelloController{}) }
好了,接下来是不是想着要重启项目?不用,bee工具默认为我们的beego项目实现了热加载,我们在来看看控制台
改动代码无需重启项目,简直不要太爽!
让后我们打开浏览器输入http://localhost:8080/hello 看结果
转自 https://www.jianshu.com/p/bdf5bc7e1c6c?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation