使用bee new
命令创建新项目,项目名称为gmms
。
$ bee new gmms
登录页面
创建登录路由
$ vim gmms/routers/router.go
package routers
import (
"gmms/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/login", &controllers.LoginController{}, "get:Login")
}
创建登录控制器与登录页面访问函数
$ vim gmms/controllers/login.go
package controllers
import "github.com/astaxie/beego"
type LoginController struct {
beego.Controller
}
func (this *LoginController) Login() {
this.TplName = "login.html"
}
创建登录视图模板
- 后台UI使用LayuiAdmin,将静态资源存放到
static/admin
目录下。
$ vim gmms/views/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>登录</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="/static/admin/layui/css/layui.css" media="all">
<link rel="stylesheet" href="/static/admin/style/admin.css" media="all">
<link rel="stylesheet" href="/static/admin/style/login.css" media="all">
</head>
<body>
<div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
<div class="layadmin-user-login-main">
<div class="layadmin-user-login-box layadmin-user-login-header">
<h2>后台管理系统</h2>
<p>欢迎使用</p>
</div>
<div class="layadmin-user-login-box layadmin-user-login-body layui-form">
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-username" for="LAY-user-login-username"></label>
<input type="text" name="username" id="LAY-user-login-username" lay-verify="required" placeholder="用户名" class="layui-input">
</div>
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-password" for="LAY-user-login-password"></label>
<input type="password" name="password" id="LAY-user-login-password" lay-verify="required" placeholder="密码" class="layui-input">
</div>
<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<label class="layadmin-user-login-icon layui-icon layui-icon-vercode" for="LAY-user-login-vercode"></label>
<input type="text" name="vercode" id="LAY-user-login-vercode" lay-verify="required" placeholder="验证码" class="layui-input">
</div>
<div class="layui-col-xs5">
<div style="margin-left: 10px;">
<img src="https://www.oschina.net/action/user/captcha" class="layadmin-user-login-codeimg" id="LAY-user-get-vercode">
</div>
</div>
</div>
</div>
<div class="layui-form-item" style="margin-bottom: 20px;">
<input type="checkbox" name="remember" lay-skin="primary" title="记住密码">
<a href="" class="layadmin-user-jump-change layadmin-link" style="margin-top: 7px;">忘记密码?</a>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit lay-filter="LAY-user-login-submit">登 入</button>
</div>
<div class="layui-trans layui-form-item layadmin-user-login-other">
<label>社交账号登入</label>
<a href="javascript:;"><i class="layui-icon layui-icon-login-qq"></i></a>
<a href="javascript:;"><i class="layui-icon layui-icon-login-wechat"></i></a>
<a href="javascript:;"><i class="layui-icon layui-icon-login-weibo"></i></a>
<a href="" class="layadmin-user-jump-change layadmin-link">注册帐号</a>
</div>
</div>
</div>
<div class="layui-trans layadmin-user-login-footer">
<p>© 2020 <a href="#" target="_blank">GMS</a></p>
</div>
</div>
<script src="/static/admin/layui/layui.js"></script>
<script>
layui.config({
base: '/static/admin/' //静态资源所在路径
}).extend({
index: 'lib/index' //主入口模块
}).use(['index', 'user'], function(){
var $ = layui.$
,setter = layui.setter
,admin = layui.admin
,form = layui.form
,router = layui.router()
,search = router.search;
form.render();
//提交
form.on('submit(LAY-user-login-submit)', function(obj){
//请求登入接口
admin.req({url: "/signin", data: obj.field, done: function(res){
console.log(res);
//请求成功后,写入 access_token
layui.data(setter.tableName, {key: setter.request.tokenName, value: res.data.access_token});
//登入成功的提示与跳转
layer.msg('登入成功', {offset: '15px', icon: 1, time: 1000}, function(){
location.href = '../'; //后台主页
});
}
});
});
//layer.msg('为了方便演示,用户名密码可随意输入', {offset: '15px',icon: 1});
});
</script>
</body>
</html>
- 浏览器访问登录页面 http://127.0.0.1:8080/login
![](https://i-blog.csdnimg.cn/blog_migrate/e94c9e48e503b0386a812cc26c53d47e.png)
登录页面
登录处理
创建路由
$ vim routers/router.go
beego.Router("/signin", &controllers.LoginController{}, "post:Signin")
创建数据库配置文件
$ vim conf/database.ini
[default]
dbdebug = true
dbalias = default
dbdriver = mysql
dbhost = 127.0.0.1
dbport = 3306
dbuser = root
dbpassword = root
dbname = gmms
dbprefix =
dbcharset = utf8mb4
dbloc = Local
maxIdleConns = 0
maxOpenConns = 0
创建数据库连接文件
$ vim models/db.go
package models
import (
"fmt"
"github.com/astaxie/beego/config"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
//定义数据库连接配置
type DbConfig struct{
Debug bool
Alias string
Driver string
DSN string
MaxOpenConns int//最大连接数
MaxIdleConns int//最大空闲连接数
}
//加载数据库配置
func load() DbConfig {
filename := "conf/database.ini"
conf, err := config.NewConfig("ini", filename)
if err != nil {
logs.Error(err)
}
fmt.Printf("\nconf = %v\n", conf)
dbdebug, err := conf.Bool("dbdebug")
if err != nil {
logs.Error(err)
}
fmt.Printf("dbdebug = %v\n", dbdebug)
dbalias := conf.String("dbalias")
dbdriver := conf.String("dbdriver")
dbhost := conf.String("dbhost")
dbport := conf.String("dbport")
dbname := conf.String("dbname")
dbuser := conf.String("dbuser")
dbpassword := conf.String("dbpassword")
dbcharset := conf.String("dbcharset")
dbloc := conf.String("dbloc")
maxIdleConns, err := conf.Int("maxIdleConns")
maxOpenConns, err := conf.Int("maxOpenConns")
if err != nil {
logs.Error(err)
}
dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=" + dbcharset + "&loc=" + dbloc
dbConfig := DbConfig{}
dbConfig.Debug = dbdebug
dbConfig.Alias = dbalias
dbConfig.Driver = dbdriver
dbConfig.DSN = dsn
dbConfig.MaxOpenConns = maxOpenConns
dbConfig.MaxIdleConns = maxIdleConns
return dbConfig
}
//初始化
func init(){
//加载配置
dbConfig := load()
//开启调试
orm.Debug = dbConfig.Debug
//注册驱动
err := orm.RegisterDriver(dbConfig.Driver, orm.DRMySQL)
if err != nil{
logs.Error(err)
}
//注册数据库
err = orm.RegisterDataBase(dbConfig.Alias, dbConfig.Driver, dbConfig.DSN, dbConfig.MaxOpenConns, dbConfig.MaxIdleConns)
if err != nil{
logs.Error(err)
}
}
创建用户模型
$ vim models/user.go
package models
import (
"github.com/astaxie/beego/orm"
"time"
)
//定义表结构
type User struct {
Id int `orm:"auto; pk"`
UserName string `orm:"size(32); unique; column(username)"`
Password string `orm:"size(255); unique"`
Email string `orm:"size(255); unique"`
CreatedAt time.Time `orm:"type(datetime); auto_now_add; null"`
UpdatedAt time.Time `orm:"type(datetime); auto_now; null"`
Status int8 `orm:"default(0)"`
}
//定义表名
func (this *User) TableName() string{
return "users"
}
//定义引擎
func (this *User) TableEngine() string{
return "INNODB"
}
//定义普通索引
func (this *User) TableIndex() [][]string{
return [][]string{
[]string{"Id", "Username"},
}
}
//初始化
func init() {
//注册模型
orm.RegisterModel(new(User))
//创建表
orm.RunSyncdb("default", false, true)
}
启动MySQL数据库服务,运行程序生成表结构。
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`status` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `password` (`password`),
UNIQUE KEY `email` (`email`),
KEY `users_id_username` (`id`,`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
创建登录处理函数
$ vim controllers/login.go
package controllers
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"gmms/models"
"strings"
)
type LoginController struct {
beego.Controller
}
func (this *LoginController) Login() {
this.TplName = "login.html"
}
func (this *LoginController) Signin(){
message := "success"
json := make(map[string]interface{})
json["code"] = 0
json["msg"] = message
//获取登录参数
username := strings.TrimSpace(this.GetString("username"))
password := strings.TrimSpace(this.GetString("password"))
fmt.Printf("username = %s, password = %s\n", username, password)
if username=="" || password==""{
message = "username or password empty"
logs.Error(message)
json["code"] = 1
json["msg"] = message
this.Data["json"] = json
this.ServeJSON()
return
}
var user models.User
user.UserName = username
ormer := orm.NewOrm()
err := ormer.Read(&user, "UserName")
if err != nil{
message = "username not exists"
logs.Error(message)
json["code"] = 1
json["msg"] = message
this.Data["json"] = json
this.ServeJSON()
return
}
if user.Password != password{
message = "password not matched"
logs.Error(message)
json["code"] = 1
json["msg"] = message
this.Data["json"] = json
this.ServeJSON()
return
}
this.Data["json"] = json
this.ServeJSON()
}