Full project address: Go-shop-B2C
preface
A mall back-end system, login is particularly important, first of all, users place orders, need to log in, background management system, need to log in. What we need to do is, in addition to login and registration, the rest of the interface needs to be login verification.
Base_controller encapsulation
Since we need to perform login verification and the Controller that does not perform login verification, and because base_controller needs to perform login verification, the Controller that does not require login verification and base_controller have common functions to call
To sum up, we should add an additional Controller for base_controller inheritance and a Controller that does not require login verification for inheritance
Let’s take a quick look at jSON_controller
json_controller
type JsonController struct {
beego.Controller
}
Copy the code
- JsonResult is returned to the front-end JSON data, and the public call function
/** * The Ajax interface returns Json */
func (c *JsonController) JsonResult(status int, errCode int, errMsg string, data ...interface{}) {
jsonData := make(map[string]interface{}, 3)
jsonData["err_code"] = errCode
jsonData["message"] = errMsg
if len(data) > 0 && data[0] != nil {
jsonData["data"] = data[0]
}
c.Ctx.Output.SetStatus(status)
c.Data["json"] = jsonData
c.ServeJSON()
}
Copy the code
- ServerError indicates a common ServerError
/** * The server reported an error */
func (c *JsonController) ServerError(err error) {
c.Ctx.Output.SetStatus(http.GetHttpStatusByAlias("internalServerError"))
logs.Error(err)
}
Copy the code
- SetSessionUser encapsulates the function that holds the session
/** * Set the login user session information */
func (c *JsonController) SetSessionUser(member models.Member) {
if member.Id <= 0 {
c.DelSession(common.SessionName)
c.DelSession("uid")
c.DestroySession()
} else {
c.SetSession(common.SessionName, member)
c.SetSession("uid", member.Id)
}
}
Copy the code
Log on to check
The Prepare function is called in Beego
The Prepare function is used for user extension purposes. This function is executed before any of the methods defined below. Users can override this function to implement user authentication and so on. Click on the jump document to see how
There are three main things to do
- Gob serialization saves user information
Ps: Serialize an object, which must be registered before encoding/ GOB decoding
- Get user information from session
- Obtain user information from cookies if login information exists in cookies
In other Controller basic writing
The main categories, controllers that require login verification and controllers that don’t, and controllers that don’t require login verification are usually controllers that contain login and registration
Controller writing that requires login verification
Address_controller, for example
Intercept some code
BaseController = BaseController = BaseController = BaseController = BaseController = BaseController = BaseController = BaseController = BaseController
type AddressController struct {
BaseController
}
// URLMapping ...
func (c *AddressController) URLMapping(a) {
c.Mapping("AddAddress", c.AddAddress)
c.Mapping("DeleteAddress", c.DeleteAddress)
c.Mapping("UpdateAddress", c.UpdateAddress)
c.Mapping("GetAllAddress", c.GetAllAddress)
}
// @title add address
// @router /add [post]
func (c *AddressController) AddAddress(a) {
var address model_views.Receiver
if v := c.GetString("address"); v ! ="" {
_ = json.Unmarshal([]byte(v), &address)
}
var receiver models.Receiver
receiver.Id = address.Id
receiver.Consignee = address.Consignee
receiver.AreaName = address.AreaName
receiver.AreaId = address.AreaId
receiver.Address = address.Address
receiver.IsDefault = address.IsDefault
receiver.Phone = address.Phone
receiver.ZipCode = address.ZipCode
receiver.MemberId = int64(c.Member.Id)
receiver.LastUpdatedBy = c.Member.Username
_, err := models.AddReceiver(&receiver)
iferr ! =nil {
// The service generally reports an error function call
c.ServerError(err)
return
}
c.JsonResult(http.GetHttpStatusByAlias("created"), http.ErrOK, http.Success, nil)}Copy the code
It’s that simple, and it’s pretty much the same for all the other controllers
Controller writing without login verification
Intercept some code
// Inherit JsonController without calling BaseController's Prepare function for login verification
type UserController struct {
JsonController
}
/ / @ Title to log in
// @router /login [post]
func (c *UserController) Login(a) {
var mobile string
var sms string
// mobile
if v := c.GetString("mobile"); v ! ="" {
mobile = v
}
// sms
if v := c.GetString("sms"); v ! ="" {
sms = v
}
smsModel, err := models.GetSmsByCodeAndMobile(sms, mobile)
iferr ! =nil {
c.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrError, http.Fail, "Phone and captcha don't match.")
return
}
ifsmsModel.ExpireDate ! =nil {
c.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrError, http.Fail, "Verification code has expired")
return
}
if smsModel.IsUsed == 1 {
c.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrError, http.Fail, "Verification code in use")
return
}
member, _ := models.GetMemberByUsername(mobile)
if member == nil {
member = &models.Member{}
}
if member.Id > 0 {
// Last login IP address
member.LoginIp = c.Ctx.Input.IP()
member.LoginDate = time.Now()
err = models.UpdateMemberById(member)
iferr ! =nil {
c.ServerError(err)
return}}else {
member.Username = mobile
member.Mobile = mobile
member.MemberRankId = 1 // Regular member
_, err := models.AddMember(member)
iferr ! =nil {
c.ServerError(err)
return}}/** * Update SMS usage */
now := time.Now()
smsModel.UsedDate = &now
smsModel.IsUsed = 1
err = models.UpdateSmsById(smsModel)
iferr ! =nil {
c.ServerError(err)
return
}
/** * Set Cookie */
c.SetSessionUser(*member)
var cookieMember CookieMember
cookieMember.MemberId = member.Id
cookieMember.Username = member.Username
cookieMember.Time = time.Now()
v, err := helpers.Encode(cookieMember)
if err == nil {
c.SetSecureCookie(common.AppKey(), "web_login", v, 24*3600)
}
commonController := &CommonController{}
memberView := commonController.setMemberByMemberModel(*member)
c.JsonResult(http.GetHttpStatusByAlias("ok"), http.ErrOK, http.Success, memberView)
}
Copy the code
conclusion
Finally, after writing these two basic controllers, it is basically to determine whether login verification is needed according to business, and then it is ok to write CRUD (add, delete, change and check) business. Yes, it is so simple