Beego Learning Notes 14:Session Control

Session Control

1> Session s are often used as global variables, such as logging the currently logged-in user or passing data between pages.

2> The session module is built in the Beego framework. Currently, the session module supports back-end engines including memory, cookie s, file s, mysql, redis, couchbase, memcache, postgres. Users can also implement their own engine based on the corresponding interface ts.If you use the red part, you need to download the corresponding session package.

3> InMain.goAdd the session-enabled method to the code.The code is as follows:

   

package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "BeegoLearn/routers"
    "github.com/astaxie/beego"
)


//Initialization
func init(){
	dbhost := beego.AppConfig.String("dbhost")
    dbport := beego.AppConfig.String("dbport")
    dbuser := beego.AppConfig.String("dbuser")
    dbpassword := beego.AppConfig.String("dbpassword")
    db := beego.AppConfig.String("db")

    //Register mysql Driver
    orm.RegisterDriver("mysql", orm.DRMySQL)
	//Construct conn connection
	//User name: Password@tcp(url address)/Database
    conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + db + "?charset=utf8"
    //Register Database Connections
    orm.RegisterDataBase("default", "mysql", conn)

    fmt.Printf("Database connection successful!%s\n", conn)  
}

func main() {
    o := orm.NewOrm()
    o.Using("default") // By default, you can specify a different database
    //Enable Session
    beego.BConfig.WebConfig.Session.SessionOn = true
	beego.Run()
}
package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "BeegoLearn/routers"
    "github.com/astaxie/beego"
)


//Initialization
func init(){
	dbhost := beego.AppConfig.String("dbhost")
    dbport := beego.AppConfig.String("dbport")
    dbuser := beego.AppConfig.String("dbuser")
    dbpassword := beego.AppConfig.String("dbpassword")
    db := beego.AppConfig.String("db")

    //Register mysql Driver
    orm.RegisterDriver("mysql", orm.DRMySQL)
	//Construct conn connection
	//User name: Password@tcp(url address)/Database
    conn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + db + "?charset=utf8"
    //Register Database Connections
    orm.RegisterDataBase("default", "mysql", conn)

    fmt.Printf("Database connection successful!%s\n", conn)  
}

func main() {
    o := orm.NewOrm()
    o.Using("default") // By default, you can specify a different database
    //Enable Session
    beego.BConfig.WebConfig.Session.SessionOn = true
	beego.Run()
}

  

4> Create a new oneLogin.goController, writing session's logical business

   

package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}
//Logon Page
func (c *LoginController) Get() {
	c.TplName = "login.html"
}
//Logon function
func (c *LoginController) Post() {
	name:=c.GetString("name")
	pwd:=c.GetString("pwd")
	islogin:=0
	if name=="admin" && pwd=="123456"{
		c.SetSession("loginuser", "adminuser")
		fmt.Println("Current session:")
		fmt.Println(c.CruSession)
	}else if name!="admin"{
		islogin=1
	}else if pwd!="123456"{
		islogin=2
	}
	c.Data["json"]=map[string]interface{}{"islogin":islogin};
	c.ServeJSON();
}
//Sign out
type LogoutController struct {
	beego.Controller
}
//Logon Exit Function
func (c *LogoutController) Post() {
	v := c.GetSession("loginuser")
	islogin:=false
	if v != nil {
	  //Delete the specified session	
	  c.DelSession("loginuser")
	  //Destroy all session s
	  c.DestroySession()
	  islogin=true
	  
	 fmt.Println("Current session:")
	 fmt.Println(c.CruSession)
	}
	c.Data["json"]=map[string]interface{}{"islogin":islogin};
	c.ServeJSON();
}

  

5> Create a new one Login.html Pages, used as presentations

<!DOCTYPE html>
 
<html>
      <head>
        <title>home page - User List Page</title>
        <link rel="shortcut icon" href="/static/img/favicon.png" /> 
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"/>
        <script type="text/javascript" src="/static/js/jquery-2.1.1.min.js"></script> 
        <script type="text/javascript" src="/static/bootstrap/js/bootstrap.min.js"></script> 
      </head>       
    <body>
       <div class="container">
              <div class="form-group">
                 <label for="text">User name:</label>
                 <input type="text" class="form-control" id="name" placeholder="User name">
              </div>
              <div class="form-group">
                 <label for="text">Password:</label>
                 <input type="text" class="form-control" id="pwd" placeholder="Password">
               </div>
               <div class="form-group">
                    <button class="btn btn-primary" onclick="login()">Land</button>
                    <button class="btn btn-default" onclick="logout()">Sign out</button>
               </div>
           <div>
                <label id="status"></label>
            </div>
       </div> 
        <!--JS Part-->
        <script type="text/javascript">
           //Logon function
           function login(){
               $.ajax({
                   type:'post',
                   url:'/Home/Login',
                   data:{
                       "name":$("#name").val(),
                       "pwd":$("#pwd").val()
                   },
                   success:function(result){
                    if(result.islogin==0){
                      $("#Status'). HTML ('logon success')  
                    }else  if(result.islogin==1){
                      $("#Status'). HTML ('user name error')  
                    } else if(result.islogin==2){
                      $("#Status'). HTML ('password error')  
                    }
                   }
               })
           }
           //Logout function
            function logout(){
               $.ajax({
                   type:'post',
                   url:'/Home/Logout',
                   data:{},
                   success:function(result){
                     if(result.islogin){
                       $("#Status'). HTML ('logout success');  
                     }else {
                      $("#Status'). HTML ('failed to log out');
                    }
                  }
               })
           }
        </script>
    </body>
</html>

  

6> Add controllers to routes, compile projects, and test runs

package routers

import (
	"BeegoLearn/controllers"
	"github.com/astaxie/beego"
)

func init() {
	//Default
	beego.Router("/", &controllers.MainController{})
	//JS Paging
	beego.Router("/Home/PageData", &controllers.UserController{})
	beego.Router("/Home/PageNextData", &controllers.YonghuController{})
	//Bootstrap usage
	beego.Router("/Home/Index", &controllers.PageController{})
	//Easyui uses
	beego.Router("/Home/EasyUI", &controllers.EasyUIController{})
	beego.Router("/Home/EasyUIData", &controllers.EasyUIDataController{})
	//File upload and download
	beego.Router("/Home/FileOpt", &controllers.FileOptUploadController{})
	beego.Router("/Home/FileDown", &controllers.FileOptDownloadController{})
	//Create, write, read, delete files
	beego.Router("/Home/FileRead", &controllers.ReadController{})
	beego.Router("/Home/FileWrite", &controllers.WriteController{})
	beego.Router("/Home/FileCreate", &controllers.CreateController{})
	beego.Router("/Home/FileDelete", &controllers.DeleteController{})
	//Api interface section
	beego.Router("/api/Html", &controllers.ApiController{})
	beego.Router("/api/GetJson", &controllers.ApiJsonController{})
	beego.Router("/api/GetXml", &controllers.ApiXMLController{})
	beego.Router("/api/GetJsonp", &controllers.ApiJsonpController{})
	beego.Router("/api/GetDictionary", &controllers.ApiDictionaryController{})
	beego.Router("/api/GetParams", &controllers.ApiParamsController{})
	//session section
	beego.Router("/Home/Login", &controllers.LoginController{})
	beego.Router("/Home/Logout", &controllers.LogoutController{})
}

  

7> The results are as follows

The initial effect of the 7-1 page is as follows:

 

7-2"Enter user name, password, click the login button

7-3"Click the exit button

 

 

 

 

8>The code for my Beego Learning Notes project has been uploaded to GitHub.The specific addresses are as follows:https://github.com/weiyunhelong/BeegoLearn

After downloading, remember to modify the configuration file of the mysql database, otherwise the project will compile without passing through it!

 

9>Next Chapter on Layout Page

Tags: Go Session Database MySQL github

Posted on Thu, 25 Jun 2020 12:20:31 -0400 by JetJagger