相对上个课程的代码,我们做一些修改。实现beego的模板应用和mysql数据库连接的简易应用。
在controllers新建一个home.go,添加:
package controllers
import (
"github.com/astaxie/beego"
)
type HomeController struct {
beego.Controller
}
func (this *HomeController) Get() {
this.TplName = "home.html"
}
routers文件下router.go需要小调
func init() {
beego.Router("/", &controllers.HomeController{})
}
改为默认homecontroller。
views文件夹下添加home.html,代码:
<!DOCTYPE html>
<html>
<head>
<title>首页 - 我的 beego 博客</title>
<link rel="shortcut icon" href="/static/img/favicon.png" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- Stylesheets -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<a class="navbar-brand" href="http://webyang.net" target="_blank">WebYang.NET</a>
<div>
<ul class="nav navbar-nav">
<li class="active"><a href="/">首页</a></li>
<li><a href="/category">分类</a></li>
<li><a href="/topic">文章</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="page-header">
<h1>三月,在成都</h1>
<h6 class="text-muted">文章发表于 2017 年 4 月 6日 11 点 31 分,共有 73 次浏览, 12 个评论</h6>
<p>
女友在成都,之前并没有去过成都。于是怀抱着一种强烈的好奇心情,来到了成都,时下赵雷的《成都》很火,让成都掀起了旅游潮。<a href='http://www.webyang.net/Html/web/article_298.html' target="_blank">更多</a>
</p>
</div>
</div>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
</body>
</html>
models文件夹下添加models.go,源码:
package models
import (
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"time"
)
const (
_DB_NAME = "root:123456@/test?charset=utf8"
_MYSQL_DRIVER = "mysql"
)
// 分类
type Category struct {
Id int64
Title string
Created time.Time `orm:"index"`
Views int64 `orm:"index"`
TopicTime time.Time `orm:"index"`
TopicCount int64
TopicLastUserId int64
}
// 文章
type Topic struct {
Id int64
Uid int64
Title string
Content string `orm:"size(5000)"`
Attachment string
Created time.Time `orm:"index"`
Updated time.Time `orm:"index"`
Views int64 `orm:"index"`
Author string
ReplyTime time.Time `orm:"index"`
ReplyCount int64
ReplyLastUserId int64
}
func RegisterDB() {
// 注册模型
orm.RegisterModel(new(Category), new(Topic))
orm.RegisterDriver(_MYSQL_DRIVER, orm.DRMySQL)
// 注册默认数据库
orm.RegisterDataBase("default", _MYSQL_DRIVER, _DB_NAME, 10)
}
最后入口文件main.go的main方法里添加:
orm.RunSyncdb("default", false, true)
运行,bee run myapp。出来如下图:

github:https://github.com/yangsir/beego_study
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/98491.html