1 注册功能

1.1 数据库配置与实现

首先传讲utils/DButil.go实现一个数据库基本连接:

package utils
import(
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"fmt"
	"database/sql"
)

var db *sql.DB

func InitMysql(){
	driverName := beego.AppConfig.String("driverName")

	// Database connect
	user := beego.AppConfig.String("mysqluser")
	pwd := beego.AppConfig.String("mysqlpwd")
	host := beego.AppConfig.String("host")
	port := beego.AppConfig.String("port")
	dbname := beego.AppConfig.String("dbname")

	dbConn := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8"
	db1, err := sql.Open(driverName, dbConn)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		db = db1
		CreateTableWithUser()
	}
} 

func ModifyDB(sql string,args ...interface{})(int64,error){
	result,err := db.Exec(sql,args...)
	if err != nil {
		log.Println(err)
		return 0, err
	}
	count, err := result.RowsAffected()
	if err != nil {
		log.Println(err)
		return 0, err
	}
	return count, nil
}

func QueryRowDB(sql string) *sql.Row{
	return db.QueryRow(sql)
}

func CreateTableWithUser(){
	sql :=`CREATE TABLE IF NOT EXISTS users(
		id INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL,
		username VARCHAR(64),
		password VARCHAR(64),
		status INT(4),
		createtime INT(10)
		);`
		ModifyDB(sql)
}

main.go里初始化 

package main

import (
	_ "myBlog/routers"
	"github.com/astaxie/beego"
	"myBlog/utils"
)

func main() {
	utils.InitMysql()
	beego.Run()
}

1.2 定义User和数据库操作方法

然后再models中创建一个user_model.go文件:

package models

import(
	"myBlog/utils"
	"fmt"
)

type User struct{
	Id int
	Username string
	Password string
	Status int // 0  normal ;1 delete
	Createtime int64
}

// insert
func InsertUser(user User)(int64,error){
	return utils.ModifyDB("insert into users(username,password,status,createtime) values (?,?,?,?)",user.Username,user.Password,user.Status,user.Createtime)
}

//condition search
func QueryUserWightCon(con string)int{
	sql := fmt.Sprintf("select id from users %s",con)
	fmt.Println(sql)
	row:=utils.QueryRowDB(sql)
	id :=0
	row.Scan(&id)
	return id
}

func QueryUserWithUsername(username string) int{
	sql := fmt.Sprintf("where username='%s'",username)
	return QueryUserWightCon(sql)
}

//login search
func QueryUserWithParam(username ,password string)int{
	sql:=fmt.Sprintf("where username='%s' and password='%s'",username,password)
	return QueryUserWightCon(sql)
}

1.3 完成conf配置文件

appname = myBlog
httpport = 8080
runmode = dev

#mysql配置
driverName = mysql
mysqluser = root
mysqlpwd = root
host = 127.0.0.1
port = 3306
dbname = mygoblog

1.4 control

在controllers包下创建一个新的controller,用来处理用户的注册:

package controllers

import (
    "github.com/astaxie/beego"
	"myBlog/models"
	"myBlog/utils"
	"fmt"
	"time"
    )

type RegisterController struct {
	beego.Controller
}

func (this *RegisterController) Get(){
	this.TplName = "register.html"
}

//处理注册
func (this *RegisterController) Post() {

	//获取表单信息
	username := this.GetString("username")
	password := this.GetString("password")
	repassword := this.GetString("repassword")
	fmt.Println(username, password, repassword)
	log.INFO(username, password, repassword)

	//注册之前先判断该用户名是否已经被注册,如果已经注册,返回错误
	id := models.QueryUserWithUsername(username)
	fmt.Println("id:", id)
	if id > 0 {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "用户名已经存在"}
		this.ServeJSON()
		return
	}

	//注册用户名和密码
	//存储的密码是md5后的数据,那么在登录的验证的时候,也是需要将用户的密码md5之后和数据库里面的密码进行判断
	password = utils.MD5(password)
	fmt.Println("md5后:", password)

	user := models.User{0, username, password, 0, time.Now().Unix()}
	_, err := models.InsertUser(user)
	if err != nil {
		this.Data["json"] = map[string]interface{}{"code": 0, "message": "注册失败"}
	} else {
		this.Data["json"] = map[string]interface{}{"code": 1, "message": "注册成功"}
	}
	this.ServeJSON()
}

为control添加路由

package routers

import (
	"myBlog/controllers"
	"github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})
	beego.Router("/register", &controllers.RegisterController{})
}

1.5 工具类

再添加一个工具类:myUtils.go

package utils

import (
	"fmt"
	"crypto/md5"
)

//传入的数据不一样,那么MD5后的32位长度的数据肯定会不一样
func MD5(str string) string{
	md5str:=fmt.Sprintf("%x",md5.Sum([]byte(str)))
	return md5str
}

1.6 前端

在views包下,创建一个html页面:register.html

$(document).ready(function () {
    //注册
    $("register-from").validate({
        rules: {
            username: {
                required: true,
                rangelength: [5, 10]
            },
            password: {
                required: true,
                rangelength: [5, 10]
            },
            repassword: {
                required: true,
                rangelength: [5, 10],
                equalTo: "#register-password"
            }
        },
        messages: {
            username: {
                required: "请输入用户名",
                rangelength: "用户名必须是5-10位"
            },
            password: {
                required: "请输入密码",
                rangelength: "密码必须是5-10位"
            },
            repassword: {
                required: "请确认密码",
                rangelength: "密码必须是5-10位",
                equalTo: "两次输入的密码必须相等"
            }
        },
        submitHandler: function (form) {
            var urlStr = "/register";
            // alert("urlStr:"+urlStr)
            $(form).ajaxSubmit({
                url: urlStr,
                type: "post",
                dataType: "json",
                success: function (data, status) {
                    alert("data:" + data.message)
                    if (data.code == 1) {
                        setTimeout(function () {
                            window.location.href = "/login"
                        }, 1000)
                    }
                },
                err: function (data, status) {
                    alert("err:" + data.message + ":" + status)
                }
            })
        }
    });
2 用户登录与session处理

2.1 登录逻辑

定义LoginController

package controllers

import (
	"github.com/astaxie/beego"
	"myBlog/models"
	"myBlog/utils"
	)

	type LoginController struct {
		beego.Controller
	}
	func (this *LoginController) Get() {
		this.TplName = "login.html"
	}

	func (this *LoginController) Post() {
		username := this.GetString("username")
		password := this.GetString("password")
		fmt.Println("username:", username, ",password:", password)
		id := models.QueryUserWithParam(username, utils.MD5(password))
		fmt.Println("id:",id)
		if id > 0 {
			this.Data["json"] = map[string]interface{}{"code": 1, "message": "登录成功"}
		} else {
			this.Data["json"] = map[string]interface{}{"code": 0, "message": "登录失败"}
		}
		this.ServeJSON()
	}

添加路由

beego.Router("/login", &controllers.LoginController{})

login.html

 

 2.2 session

1)启用session

首先我们在登录的时候添加session。先修改配置文件打开session,打开conf包下的app.conf文件,添加一行:

sessionon = true

或者在main.go中打开session:

func main() {
	utils.InitMysql()
	beego.BConfig.WebConfig.Session.SessionOn = true // 打开session
	beego.Run()
}

2)登录功能添加Session处理

 3)重新设置路由,当访问/,这个根路径的时候,我们表示访问首页。

 4)添加基础控制base_controller.go

package controllers

import (
	"github.com/astaxie/beego"
	"fmt"
)

//先定义个BaseController,里面额外设置两个字段,IsLogin表示用户是否登录,Loginuser表示用户名。
type BaseController struct {
	beego.Controller
	IsLogin   bool
	Loginuser interface{}
}

//判断是否登录,重写Prepare()方法,用于获取session。
func (this *BaseController) Prepare() {
	loginuser := this.GetSession("loginuser")
	fmt.Println("loginuser---->", loginuser)
	if loginuser != nil {
		this.IsLogin = true
		this.Loginuser = loginuser
	} else {
		this.IsLogin = false
	}
	this.Data["IsLogin"] = this.IsLogin
}

5)添加首页控制home_controller.go

package controllers
import (
	"fmt"
)

type HomeController struct {
	//beego.Controller
	BaseController
}

func (this *HomeController) Get() {
	fmt.Println("IsLogin:",this.IsLogin,this.Loginuser)
	this.TplName = "home.html"
}

6)前端设计

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <link href="../static/css/blogsheet.css" rel="stylesheet">
</head>
<body>
{{template "block/nav.html" .}}
</body>
</html>

 nav.html

<div id="nav">
    <div id="nav-write-article">
        <ul>
        {{/*如果已经登录,才会显示"写博客"*/}}
        {{if .IsLogin}}
            <li><a href="/article/add">写博客</a></li>
        {{end}}
        </ul>
    </div>


    <div id="nav-menu">
        <ul>
            <li><a href="/">首页</a></li>
            <li><a href="/tags">标签</a></li>
            <li><a href="/album">相册</a></li>
            <li><a href="/aboutme">关于我</a></li>
        </ul>
    </div>
</div>

效果