当前位置:网站首页>Go+mysql+redis+vue3 simple chat room, the second bullet: database links and operations
Go+mysql+redis+vue3 simple chat room, the second bullet: database links and operations
2022-07-18 10:33:00 【Game programming】
Setup profile
Create in the root directory config Catalog , The directory stores some configuration files needed by the global
create profile config.ini
# The configuration file [mysql]Db = mysqlHost = 127.0.0.1Port = 3306User = rootPwd = root#DbName = beeDbName = gochat[redis]Db = redisAddr = 127.0.0.1:6379Pwd = rootDbName = 1Create... For parsing configuration files config.go
package configimport "gopkg.in/ini.v1"// Global profile The pointer var ConfigFile *ini.Filefunc init(){ // download ini package // First execution go get command , It has to be executed first :go env -w GOSUMDB="sum.golang.google.cn // The purpose is to modify GOSUMDB Verify address , The default address is the wall , It will cause connection timeout // And then execute //go get gopkg.in/ini.v1 if file,err := ini.Load("./config/config.ini");err != nil{ panic(err) }else{ ConfigFile = file }}Connect to database
Created in the root directory models Catalog , Deposit mysql Relevant operation documents
establish mysql.go
package modelsimport ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "project1/config" "time")func GetMysql() *gorm.DB{ host := config.ConfigFile.Section("mysql").Key("Host").String() user := config.ConfigFile.Section("mysql").Key("User").String() pwd := config.ConfigFile.Section("mysql").Key("Pwd").String() dbName := config.ConfigFile.Section("mysql").Key("DbName").String() port := config.ConfigFile.Section("mysql").Key("Port").String() db,err := gorm.Open("mysql",user+":"+pwd+"@tcp("+host+":"+port+")/"+dbName+"?charset=utf8mb4&parseTime=True") if err != nil { panic(err) } db.SingularTable(true)// Do not add s db.DB().SetMaxIdleConns(20)// Number of connection pools db.DB().SetMaxOpenConns(100)// Maximum concurrency db.DB().SetConnMaxLifetime(time.Second*30)// Link timeout return db // Back to Conn It can only be used once goroutine The operation of , That is to say, you can't put this Conn be applied to Go The multiple goroutine Inside . //Go I don't know which operation is caused by goroutine Sponsored , This leads to a number of According to chaos , For example, it might put goroutineA The result of the query operation performed inside is returned to goroutineB So that B Mistakenly regard this result as self executing insert data .}Create data table model
gorm Operation data sheet , It's based on a struct Variable of type ,struct The attributes and types in the need to be one-to-one corresponding to the table , So you need to create two files , Equivalent to the corresponding table model, Used to declare and operate on two tables
First create two tables ,user and msg


stay models Create under folder user.go file , as follows
package models// Introduce the required package import ( "crypto/md5" "fmt" "github.com/go-playground/validator/v10" "github.com/jinzhu/gorm" "github.com/gin-gonic/gin")// Create custom types User , Capitalization , So that the external needs to reference this type type User struct{ //gorm.Model by gorm Predefined mysql Field , It includes ,ID,CreateAt,UpdateAt,DeleteAt Four fields . Don't have to , Completely define yourself . But use gorm deleted , Unable to automatically mark soft deletion gorm.Model // All attributes are capitalized , Convenient for external calls //tag It is mainly used for gorm Build table , No need to use gorm If you build a table , Don't write tag. Although the attribute is capitalized , But when creating a table, the fields will be converted to lowercase and underlined Phone string `gorm:"size:11;not null;unique_index"` Password string `gorm:"type:varchar(50);not null;"` Name string `gorm:"type:varchar(30);default:'';"`}// Register new users // Can be found in api Call this method after the validation data passes //*RegisterRule by gin After the framework validation parameters pass , Created with incoming parameters RegisterRule Variable pointer of type func (user *RegisterRule) RegisterUser(){ var userModel User var back Response // Encrypted password md5Pwd := md5.Sum([]byte(rule.Password+"12345")) // md5.Sum Back to a [16]byte Array , Can't use string() Direct conversion newPwd := fmt.Sprintf("%x",md5Pwd) // Set the field values to be inserted into the table userModel = User{Phone:rule.Phone,Password:newPwd,Name:rule.Name} // Get one mysql Connect mysql := GetMysql() defer mysql.Close() // insert data if err := mysql.Create(&userModel).Error;err == nil { back = gin.H{"status":1,"msg":" Registered successfully ","data":userModel} }else{ back = gin.H{"status":0,"msg":err.Error()} } return back}// Login method func (rule *LoginRule) Login() Response{ var user User // Encrypted password md5Pwd := md5.Sum([]byte(rule.Password+"12345")) newPwd := fmt.Sprintf("%x",md5Pwd) // Query the user mysql := GetMysql() defer mysql.Close() if err := mysql.Where("phone = ? AND password = ?",rule.Phone,newPwd).First(&user).Error;err == nil{ back = gin.H{"status":1,"msg":" Login successful ","data":user} }else{ back = gin.H{"status":0,"msg":err.Error()} } return $back;}Use models The method in
After defining the registration method , We are here api/user.go In file , Use models The method in , as follows
import( ... "project1/models")// Registration method func Register(c *gin.Context){ ... // Perform verification reception if err := c.ShouldBind(®isterRule);err == nil { // Data validation succeeded , Call the registration method res := registerRule.Register() if res.status == 1{ c.JSON(200,res) }else{ c.JSON(402,res) } }else{ c.JSON(402,err.Error()) }}// Login method // according to Register technological process , Try to establish a login method func Login(c *gin.Context){ // First in api/user.go Define login parameter validation structure LoginRule // Then execute in this method ShouldBind Method , Verify and get parameters // After successful verification , call LoginRule Binding method , Method defined in models/user.go in // According to the return status , Determine whether the login is successful and other subsequent operations }author :whynogome
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- 多面手程序员
- 2022-7-11 pcl double free or corruption(out) . valgrind. -march=native
- Fan in and fan out mode of asynchronous API design
- Yuancosmos daily | the British court approved the provision of litigation documents through NFT for the first time; South Korea Ministry of science and Technology Cheng Liyuan universe /nft Safety Com
- Maxwell配置案例
- 巯基化金属有机骨架吸附剂([email protected])|[email protecte
- 齐岳:纳米银颗粒负载UiO-66|[email protected]|[email p
- Metal organic framework material [email protected] |
- 史上最全CAD快捷键大全汇总
- 五种常见的加密方式及常用的加解密工具
猜你喜欢

有机金属框架MIL-53(Fe)负载碳纳米管复合物|ZIF-8负载717树脂复合材料|Ru纳米粒子负载MIL-53(Cr),MIL-53(Cr)
[email protected]|金属有机骨架复合物UiO-66-NH2/MoS2|PPS-ZIF-8-BSA|PVA/UiO-66|[email protected]|

Summary of thread synchronization

Cloud computing in China: prospects for 2025

With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development

标题太长用省略号代替

中国云计算:2025年展望

Salary increase skills, this is a useful visualization, you can only be "face Engineering"
[email protected] |Nh2-mil-53 (SC) | nh2-mil-53 (AL) | nh2-mil-125 loaded silver cobalt alloy nano material | aminate"/>Fe3O4 [email protected] |Nh2-mil-53 (SC) | nh2-mil-53 (AL) | nh2-mil-125 loaded silver cobalt alloy nano material | aminate
[email protected]复合材料"/>金属-有机骨架材料UiO-66(Hf)|Cu(II)-NH2-MIL-125/TiO2纳米棒复合材料|PDMS/[email protected]复合材料
随机推荐
基于HDP构建企业数据平台
8 年产品经验,我总结了这些持续高效研发实践经验 · 研发篇
Metal organic framework mil-101 (CR) loaded chitosan | MOF modified Cu2O nanowires | MOF derived TiO2 modified graphite phase carbon nitride
Count the number of MySQL groups, and then calculate the proportion of each group
搭建Sky Hackathon参赛环境
mysql中校验一条数据中所有字段是否完整
Co-MIL-53(Fe)-NH2/UIO-66-NH2| [email protected] (Fe)|
mysql分组后统计个数,然后计算出每组个数占比
DataTime module, OS module, Sys module, JSON module, JSON module operation of time module
Easymock, easymock class extension, and powermock
APP上架因收集个人信息问题被拒绝该怎么解决?
金属有机骨架复合材料|Ag-UiO-66-NH2|[email protected]/gC3N4|[email p
Fan in and fan out mode of asynchronous API design
三菱PLC信号处理系列之浮点数波动抑制(梯形图)
用户积分功能的设计
Metal organic framework material uio-66 (HF) | Cu (II) -nh2-mil-125/tio2 nanorod composite | pdms/pcn- [email protected] compound
时间模块之datatime模块、os模块、sys模块、json模块、json模块实操
How to solve the problem of APP being rejected for collecting personal information?
Mysql database, PostgreSQL database, a statement can be updated if there is duplicate data, without adding on duplicate key update name=values (name)
史上最全CAD快捷键大全汇总