Using wego framework to realize user login function

introduce

This paper illustrates how to use wego framework to realize user login function through a simple example. The main functions are as follows:

  1. When a user accesses a page requiring login authentication, he will first check the login account of the session. If there is no login account, he will jump to the login page.
  2. After the user submits the login page, verify whether it is a legal user. If it passes the verification, save the user account to the session and jump to the index page.

Note: this example uses session based on cookie engine

Structure of the project

demo
├── controller          - Controller directory
│   └── base.go         - Controller Foundation struct
│   └── home.go         - home controller
│   └── login.go        - Log in to the relevant processor
├── models              - Model catalog
├── logs                - Log file directory
├── static              - Static resource directory
│   ├── css
│   ├── img
│   └── js
├── view                - View template directory
│   └── login.html
│   └── index.html
├── app.conf            - Application profile
└── main.go             - Entry file

Contents of the configuration file

#apply name
app_name = demo

[server]
#http listening port
http_port = 8080

[session]
#Whether the session is enabled
session_on = true
#session type
session_store=cookie
#The name of the client's cookie
cookie_name = "wego"
#session expiration time, in seconds
life_time = 3600
#hash string of session data
hash_key = 123456

Key notes:

  • http_port = 8080
    < < the service will listen on port 8080
  • [session]
    < < used to set whether to start the session and set the cache engine corresponding to the session. In this example, cookie based session is used

main file

package main

import (
	"demo/controller"
	"github.com/haming123/wego"
	log "github.com/haming123/wego/dlog"
)

func main() {
	web, err := wego.InitWeb()
	if err != nil{
		log.Error(err)
		return
	}

	web.GET ("/show_login", controller.HandlerShowLogin)
	web.POST("/login_post", controller.HandlerLoginPost)
	web.GET ("/index", (*controller.HomeController).ShowHome)

	err = web.Run()
	if err != nil {
		log.Error(err)
	}
}

Login logic

When a user accesses a page requiring login verification, he will first check the login account of the session. If there is no login account, he will jump to the login page. The routing registration code of the login page is:

web.GET ("/show_login", controller.HandlerShowLogin)

controller. Handler showlogin registers a functional processor for "/ show_login": controller HandlerShowLogin:

func HandlerShowLogin(c *wego.WebContext) {
	c.WriteHTML(http.StatusOK, "./view/login.html", nil)
}

login. The contents of HTML are as follows:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login page</title>
</head>
<body>
    <h2>User login</h2>
    <form action="/login_post" method="post">
        <div>User account:</div>
        <div>
            <input type="text" name="account" placeholder="Please enter user account" />
        </div>
        <br />
        <div>Login password:</div>
        <div>
            <input type="password" name="password" placeholder="Please enter the login password"/>
        </div>
        <br />
        <div>
            <input type="submit" value="Log in now" />
        </div>
    </form>
</body>
</html>

After the user clicks "log in now", the server sends a post request: / login_ post, /login_ Route registration code of post request:

web.POST("/login_post", controller.HandlerLoginPost)

controller.HandlerLoginPost is a functional processor:

func HandlerLoginPost(c *wego.WebContext) {
	account := c.Param.MustString("account")
	password := c.Param.MustString("password")
	if account == "admin" && password == "demo" {
		c.Session.Set("account", account)
		c.Session.Save()
		c.Redirect(302, "/index")
	} else {
		c.Session.Set("account", "")
		c.Session.Save()
		c.Redirect(302, "/show_login")
	}
}

Key notes:

  • Through c.param Muststring function to get the form parameter
  • Save the account to the session after the verification is passed
  • Check the "account" and "password" parameters. If they pass the verification, jump to "/ index", otherwise the login page will be displayed: "/ show_login"

Display the / index page

Implement BaseController

Only users who have passed login authentication can access the / index page. Therefore, when displaying the / index page, you need to check the session data. If there is an account, you can access the / index page. Otherwise, jump to / show_login page

Login verification logic can be implemented for each page that needs to log in. Although this method is feasible, it is cumbersome to implement. We can use the interceptor of wego framework to simplify the implementation of login verification. Wego provides two kinds of interceptors:

  1. Functional interceptor
  2. Interface interceptor
    In this example, we use the interface interceptor to realize login verification. First, we define a basic struct: BaseController, and implement the interceptor interface in BaseController: BeforeExec(ctx *wego.WebContext):
type BaseController struct {
	Account string
}

func (this *BaseController) BeforeExec(ctx *wego.WebContext) {
	account, err := ctx.Session.GetString("account")
	if err != nil || account == "" {
		ctx.Redirect(302, "/show_login")
		return
	}
	this.Account = account
}

In this way, if a struct is combined with BaseController, it will have BeforeExec method. Users will first access BeforeExec method when accessing the processor, so that they can share the login verification logic, do not need to repeat the implementation in each processor, and greatly simplify the coding.

Implement HomeController

In order to share login verification logic, BaseController needs to be combined in HomeController first:

type HomeController struct {
	BaseController
}

Next is the processor code of the / index page:

func (this *HomeController) ShowHome(c *wego.WebContext) {
	c.WriteHTML(http.StatusOK, "./view/index.html", this.Account)
}

(this *HomeController)ShowHome is a method processor that reads the index in ShowHome HTML template and use this Account for rendering. index. The contents of the HTML template are as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    hello : {{.}}
</body>
</html>

Keywords: Go Back-end

Added by CanMan2004 on Mon, 21 Feb 2022 05:04:16 +0200