How to log in as golang user
The method for golang to implement user login registration is as follows:
The first step is to register models
Create models.go under models
models.go File
package models import ( "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func RegisterDB() { //注册驱动 orm.RegisterDriver("mysql", orm.DRMySQL) //数据库链接 //注册默认数据库 var db_url string = beego.AppConfig.String("username_DB") + ":" + beego.AppConfig.String("password_DB") + "@tcp(" + beego.AppConfig.String("host_DB") + ")/" + beego.AppConfig.String("name_DB") + "?charset=" + beego.AppConfig.String("charset") beego.Info(db_url) orm.RegisterDataBase("default", "mysql", db_url) // orm.RegisterDataBase("default", "mysql", "an:111@tcp(127.0.0.1:3306)/yoo_home?charset=utf8") // //注册model orm.RegisterModel(new(TUser)) }
The second step requires database connection
The app.conf file under conf
appname = an httpport = 8080 runmode = dev sessionon = true #数据库为mysql host_DB = "127.0.0.1" port_DB = "3306" charset = "utf8" name_DB = "ancg" username_DB = "an" password_DB = 111
The third step writes a simple front-end view interface
## Create the client.html file under #views<!DOCTYPE html> <html> <head> <title>客户端接口测试</title> </head> <body> <label>注册</label> <form action="/client " method="POST"> <label>[options == register 注册]</label> <div>options:<input type="text" value="register" name="options"></div> <div>tel:<input type="text" name="Tel"></div> <div>pwd:<input type="text" name="Pwd"></div> <input type="submit" name="注册"Submit/> </form> <br> <label>登录</label> <form action="/client " method="POST"> <label>[options == login 登录]</label> <div>options:<input type="text" value="login" name="options"></div> <div>tel:<input type="text" name="Tel"></div> <div>pwd:<input type="text" name="Pwd"></div> <input type="submit" name="注册"Submit/> </form> </body> </html>
package models import ( "github.com/astaxie/beego/orm" //_"github.com/go-sql-driver/mysql" ) //用户表 type TUser struct { //用户序号 Id int64 //电话号码 Tep string //密码 Pwd string //收款人 Payee string //地址 Address string //收款帐号 Amount string //账号类别 AmountType string //是否消费者 IsCustomer bool //是否商家 IsSeller bool //是否配送员 IsDiliver bool //是否管理员 IsManager bool //微信openId Vid string //是否冻结 IsLock bool //创建时间 --- 时间戳 AddTime int64 } //新建用户 func AddUser(user *TUser) (int64, error) { o := orm.NewOrm() //数据库 userId, err := o.Insert(user) //插入数据 return userId, err } //查询账号 func GetUserById(userId int64) (*TUser, error) { o := orm.NewOrm() //数据库 user := new(TUser) //TUser就是第9行struct的数据库,就是mysql的表 qs := o.QueryTable("t_user") //表名为t_user err := qs.Filter("id", userId).One(user) //One是指查询一条数据,One(user)是查询mysql表中一条数据 return user, err } //手机号查询账号 func GetUserByTel(tel string) (*TUser, error) { o := orm.NewOrm() user := new(TUser) //TUser就是第9行struct的数据库,就是mysql的表 qs := o.QueryTable("t_user") //表名为t_user err := qs.Filter("tel", tel).One(user) //One是指查询一条数据,One(user)是查询mysql表中一条数据 return user, err } //微信Id查询账号 func GetUserByVid(vid int64) (*TUser, error) { o := orm.NewOrm() user := new(TUser) //TUser就是第9行struct的数据库,就是mysql的表 qs := o.QueryTable("t_user") //表名为t_user err := qs.Filter("vid", vid).One(user) //One是指查询一条数据,One(user)是查询mysql表中一条数据 return user, err }
package controllers import ( "github.com/astaxie/beego" "time" ) type ClientController struct { beego.Controller } func (this *ClientController) Get() { this.TplName = "client.html" } func (this *ClientController) Post() { options := this.Input().Get("options") beego.Info(options) //请求检查方法 if options != "" { switch options { case "login": this.login() case "register": this.register() default: this.Data["json"] = map[string]interface{}{"status": 400, "msg": "无对应处理方法!", "time": time.Now().Format("2006-12-12 12:12:12")} this.ServeJSON() return } this.Data["json"] = map[string]interface{}{"status": 400, "msg": "options为空", "time": time.Now().Format("2006-12-12 12:12:12")} this.ServeJSON() return } }
golang tutorial column .
The above is the detailed content of How to log in as golang user. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
