beego框架是比较优秀的golang后端框架,由于最近项目需要做一个后端服务,所以选择了beego,参考了不少网上资料。
参考资料:https://beego.me/docs/intro/
安装beego
beego安装还是挺简单的,直接github下载源码或者go get都可以。
beego源码github:https://github.com/astaxie/beego
beego官网:https://beego.me/
一般来说,类似MVC模式,beego项目有如下结构
├── conf
│ └── app.conf
├── controllers
│ ├── admin
│ └── default.go
├── main.go
├── models
│ └── models.go
├── static
│ ├── css
│ ├── ico
│ ├── img
│ └── js
└── views
├── admin
└── index.tpl
功能逻辑如下
一目了然。
安装bee
bee是beego的一个项目管理工具,使用go get安装
go get github.com/beego/bee
然后配置路径文件,mac下打开终端运行
atom ~/.bash_profile
最后加入下面两行:
export GOPATH=${HOME}/go
export PATH=${PATH}:${GOPATH}/bin
再在终端输入:
source ~/.bash_profile
这样子bee安装就完成了。
终端输入bee,看到以下信息:
ok,使用bee new命令试一试。终端输入:
打开gopath下的src,看到有个test文件夹,目录信息如下:
跟上面的结构一致,试试run它吧
运行beego项目
我们在controllers文件夹下新建一个hello.go,它的代码如下:
package controllers
import (
"github.com/astaxie/beego"
)
type HelloController struct {
beego.Controller
}
func (c *HelloController) Get() {
c.Ctx.WriteString("hello world!\n" + "this is test beego!")
}
再在routers的router.go里面添加代码:
beego.Router("/hello", &controllers.HelloController{})
这样子localhost:8080/hello这个地址就定向到了HelloController的内容去了。
终端输入:
go run main.go
打印如下信息:
浏览器打开localhost:8080端口:
切换到localhost:8080/hello:
至此,mac上的一个beego环境就搭建完毕。