当前位置:网站首页>The practice of the beego framework for goweb development: Section V project construction and user registration
The practice of the beego framework for goweb development: Section V project construction and user registration
2022-07-28 17:20:00 【qfliweimin】
One 、 Set up the project
First open the terminal and enter gopath Under the src Catalog , Then execute the following command , Create a beego project :
bee new myblogwebThe operation effect is as follows :

And then through goland Open the project :

We turn on conf The configuration file under the package :app.conf file , Change the port number to 8080:
appname = myblogweb
httpport = 8080
runmode = devThen enter the project directory in the terminal , And then run the project :

We can see , The project has been running , And monitor on 8080 On the port of . Next, we open the browser and enter the website :http://127.0.0.1:8080/, Then you can see the welcome interface :

Two 、 Registration function
2.1model
First, let's create a database :

Let's create a toolkit first utils, And then create a go file , Used to do mysql Tool class of , It provides the functions of connecting databases and creating tables .
First, provide an initialization method :
func InitMysql() {
fmt.Println("InitMysql....")
driverName := beego.AppConfig.String("driverName")
// Register database driver
orm.RegisterDriver(driverName, orm.DRMySQL)
// Database connection
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 := "root:[email protected](127.0.0.1:3306)/cmsproject?charset=utf8"
dbConn := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8"
//dbConn := "root:[email protected](127.0.0.1:3306)/cmsproject?charset=utf8"
dbConn := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + dbname + "?charset=utf8"
db, _ = sql.Open(driverName, dbConn)Then design the data table , We need users id, And as the primary key , user name username And password password, And the state status, This is used to mark whether the user has been deleted ,0 Indicates normal state ,1 Said to delete . And the registration time , We can use integer timestamp to express , therefore sql The statement is as follows : You can directly operate the database creation , It can also be created by code :
// Create a user table
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)
}Then provide a method , Used to perform sql sentence :
// Operating the database
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
}One more way , Used for subsequent database operations :
// Inquire about
func QueryRowDB(sql string) *sql.Row{
return db.QueryRow(sql)
}And then again models Create a model file :
package models
import (
"myblogweb/utils"
"fmt"
)
type User struct {
Id int
Username string
Password string
Status int // 0 The normal state , 1 Delete
Createtime int64
}
//-------------- Database operation -----------------
// 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)
}
// Query by criteria
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
}
// Query according to user name id
func QueryUserWithUsername(username string) int{
sql := fmt.Sprintf("where username='%s'",username)
return QueryUserWightCon(sql)
}
// According to user name and password , Inquire about id
func QueryUserWithParam(username ,password string)int{
sql:=fmt.Sprintf("where username='%s' and password='%s'",username,password)
return QueryUserWightCon(sql)
}2.2 view
We first in views It's a bag , Create a html page :register.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> register </title>
<link rel="stylesheet" type="text/css" href="../static/css/lib/login.css">
<link rel="stylesheet" type="text/css" href="../static/css/blogsheet.css">
<script src="../static/js/lib/jquery-3.3.1.min.js"></script>
<script src="../static/js/lib/jquery.url.js"></script>
<script src="../static/js/blog.js"></script>
</head>
<body>
<div id="nav">
<div id="nav-login">
<ul>
<li><a href="/login"> Sign in </a></li>
<li><a href="/register"> register </a></li>
</ul>
</div>
</div>
<div class="htmleaf-container">
<div class="wrapper">
<!-- Registration Form -->
<div class="container">
<h1>Welcome</h1>
<form id="register-form" class="form">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password" id="register-password">
<input type="password" name="repassword" placeholder="rePassword">
<br>
<button type="submit" id="login-button">Register</button>
</form>
</div>
{
{/* Background animation */}}
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</body>
</html>Page effects :

Add form validation :
We use jquery To achieve js part , stay js Under the table of contents , Create subdirectories lib, Put... In it jquery Framework documents , And introduce... In the page .
Then recreate a js file :blog.js
First, add form validation :
$(document).ready(function () {
// Registration form verification
$("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:" Please enter a user name ",
rangelength:" User name must be 5-10 position "
},
password:{
required:" Please input a password ",
rangelength:" The password must be 5-10 position "
},
repassword:{
required:" Please confirm the password ",
rangelength:" The password must be 5-10 position ",
equalTo:" The two passwords must be the same "
}
},
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)
}
})
}
})
})
When the user clicks on the form submit Button , Will jump to /register route , Because it is set to post request , So we can post Complete the registration of the form . If the registration is successful , And then jump to /login route .
2.3 controller
We are controllers Create a new... Under the package controller, Used to handle user registration :
package controllers
import "github.com/astaxie/beego"
type RegisterController struct {
beego.Controller
}
func (this *RegisterController) Get(){
this.TplName = "register.html"
}
func (this *RegisterController) Post() {
// Get form information
username := this.GetString("username")
password := this.GetString("password")
repassword := this.GetString("repassword")
fmt.Println(username, password, repassword)
log.INFO(username, password, repassword)
// Before registering, judge whether the user name has been registered , If you have already registered , Returns an error
id := models.QueryUserWithUsername(username)
fmt.Println("id:", id)
if id > 0 {
this.Data["json"] = map[string]interface{}{"code": 0, "message": " The user name already exists "}
this.ServeJSON()
return
}
// Register user name and password
// The stored password is md5 Later data , Then, during login verification , It is also necessary to change the user's password md5 Then judge with the password in the database
password = utils.MD5(password)
fmt.Println("md5 after :", 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": " Registration failed "}
} else {
this.Data["json"] = map[string]interface{}{"code": 1, "message": " Registered successfully "}
}
this.ServeJSON()
}
Next , We need to register a new route , modify router.go file :
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/register", &controllers.RegisterController{})
}And then we create one Post() Method , Used for processing post Request :
// Deal with registration
func (this *RegisterController) Post() {
// Get form information
username := this.GetString("username")
password := this.GetString("password")
repassword := this.GetString("repassword")
fmt.Println(username, password, repassword)
// Before registering, judge whether the user name has been registered , If you have already registered , Returns an error
id := models.QueryUserWithUsername(username)
fmt.Println("id:",id)
if id > 0 {
this.Data["json"] = map[string]interface{}{"code":0,"message":" The user name already exists "}
this.ServeJSON()
return
}
// Register user name and password
// The stored password is md5 Later data , Then, during login verification , It is also necessary to change the user's password md5 Then judge with the password in the database
password = utils.MD5(password)
fmt.Println("md5 after :",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":" Registration failed "}
}else{
this.Data["json"] = map[string]interface{}{"code":1,"message":" Registered successfully "}
}
this.ServeJSON()
}The idea is to receive the form information first , Then judge whether the user name already exists in the database , If it already exists , Then you cannot register , We can go through json Return information : The user name already exists .
Otherwise, register , For the sake of password security , We can store passwords in the database md5 Encrypt data .
So in the toolkit , Add another tool class :myUtils.go
package utils
import (
"fmt"
"crypto/md5"
)
// The incoming data is different , that MD5 After 32 Bit length data will certainly be different
func MD5(str string) string{
md5str:=fmt.Sprintf("%x",md5.Sum([]byte(str)))
return md5str
}
2.3 function
We turn on the terminal , Enter the directory where the project is located , Carry out orders :
bee run
After the project starts , Monitor in 8080 On port .
And executed InitMysql() Method , Initialize database , We open the database to refresh , A data table has been created user:

Open the browser , Enter the following URL :http://localhost:8080/register , Then enter the user name and password to register .


here , You can experiment repeatedly , For example, the user name is not long enough , The repeated passwords are inconsistent , Same user name, etc .
边栏推荐
- Re11: read EPM legal judgment prediction via event extraction with constraints
- Ugui learning notes (IV) ugui event system overview and Usage Summary
- MySQL详细学习教程(建议收藏)
- Codeforces round 770 (Div. 2) e. fair share
- Algorithm learning: leetcode interview question 09. implement queue with two stacks
- 一文了解 Kubernetes 中的服务发现
- Unity3d shader achieves ablation effect
- Games101 assignment04 job 04
- Reasoning Over Semantic-Level Graph for Fact Checking
- 软考回顾总结
猜你喜欢

influxdb2的使用

valarray数值库学习

使用阿里云免费的SSL证书

Application of Pegasus d200s UAV and airborne lidar in large-scale DEM construction

Ugui learning notes (II) Scrollview related

kubernetes service 原理解析

HTAP comes at a price

: No such file or directory
![[deep learning]: day 6 of pytorch introduction to project practice: multi-layer perceptron (including code)](/img/19/18d6e94a1e0fa4a75b66cf8cd99595.png)
[deep learning]: day 6 of pytorch introduction to project practice: multi-layer perceptron (including code)

Easypoi multi sheet export by template
随机推荐
Goweb开发之Beego框架实战:第四节 数据库配置及连接
Janus series article 3 API usage guide videoroom creating a new video room
Record the processing process of CEPH two RBDS that cannot be deleted
HTAP comes at a price
Goweb开发之Iris框架实战:项目总结与回顾
Unity3d shader achieves ablation effect
Ugui learning notes (III) summary of the use of each control
C#遍历集合
C # traversal set
充分利用----英文
It is said that NVIDIA has held talks with Softbank and will offer more than US $32billion to acquire arm
Goweb开发之Beego框架实战:第四节 数据库配置及连接
Modeling Semantics with Gated Graph Neural Networks for KBQA
Codeworks round 801 (Div. 2) and epic Institute of technology round D. tree queries (tree DP)
Codeforces round 770 (Div. 2) e. fair share
Andthen of function interface
Easypoi multi sheet export by template
[deep learning]: day 5 of pytorch introduction to project practice: realize softmax regression from 0 to 1 (including source code)
Proof of the third scene (f) in 22 years
Unity shader transparent effect