当前位置:网站首页>Go language web development series 29: Gin framework uses gin contrib / sessions library to manage sessions (based on cookies)
Go language web development series 29: Gin framework uses gin contrib / sessions library to manage sessions (based on cookies)
2022-07-03 13:48:00 【Lao Liu, you are so awesome】
One , Libraries used for installation :
1, The address of the library :
https://github.com/gin-contrib/sessions
2, Install... From the command line :
[email protected]:~$ go get -u github.com/gin-contrib/sessions explain : Liu Hongdi's go The forest is a focus golang The blog of ,
Address :https://blog.csdn.net/weixin_43881017
explain : author : Liu Hongdi mailbox : [email protected]
Two , Information about the demonstration project
1, Address :
https://github.com/liuhongdi/digv29
2, Functional specifications : Demonstrated in gin Under the framework of session The interview of
3, Project structure : Pictured :

3、 ... and ,go Code instructions
1,router/router.go
package router
import (
// Import session package
"github.com/gin-contrib/sessions"
// Import session Storage engine
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv29/controller"
"github.com/liuhongdi/digv29/global"
"log"
"net/http"
"runtime/debug"
)
func Router() *gin.Engine {
router := gin.Default()
// Handling exceptions
router.NoRoute(HandleNotFound)
router.NoMethod(HandleNotFound)
//use middleware
router.Use(Recover)
// be based on cookie establish session Storage engine for , Pass a parameter , Used as the key for encryption
store := cookie.NewStore([]byte("secret1234"))
//session Middleware validation , Parameters mysession, It's the browser side cookie Name
router.Use(sessions.Sessions("mysession", store))
//static
router.StaticFS("/static", http.Dir("/data/liuhongdi/digv29/static"))
// Path mapping :index
userc:=controller.NewUserController()
router.POST("/user/login", userc.Login);
router.GET("/user/session", userc.Session);
router.GET("/user/logout", userc.Logout);
return router
}
func HandleNotFound(c *gin.Context) {
global.NewResult(c).Error(404," Resource not found ")
return
}
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// Print error stack information
log.Printf("panic: %v\n", r)
debug.PrintStack()
global.NewResult(c).Error(500," Server internal error ")
}
}()
// Finished loading defer recover, Continue with subsequent interface calls
c.Next()
}2,controller/userController.go
package controller
import (
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv29/global"
)
type UserController struct{}
func NewUserController() UserController {
return UserController{}
}
// Sign in
func (g *UserController) Login(c *gin.Context) {
username := c.PostForm("username")
password := c.PostForm("password")
result := global.NewResult(c)
if (username == "lhd" && password=="123") {
//set session
session := sessions.Default(c)
session.Set("username", username)
session.Save()
result.Success("success");
} else {
result.Error(1," Wrong username and password ");
}
return
}
// read session
func (g *UserController) Session(c *gin.Context) {
//get session
session := sessions.Default(c)
username := session.Get("username")
result := global.NewResult(c)
result.Success(username);
return
}
//logout
func (g *UserController) Logout(c *gin.Context) {
//clear session
session := sessions.Default(c)
session.Clear()
session.Save()
result := global.NewResult(c)
result.Success("success");
return
}3,global/result.go
package global
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Result struct {
Ctx *gin.Context
}
type ResultCont struct {
Code int `json:"code"` // Self increasing
Msg string `json:"msg"` //
Data interface{} `json:"data"`
}
func NewResult(ctx *gin.Context) *Result {
return &Result{Ctx: ctx}
}
// Return to success
func (r *Result) Success(data interface{}) {
if (data == nil) {
data = gin.H{}
}
res := ResultCont{}
res.Code = 0
res.Msg = ""
res.Data = data
r.Ctx.JSON(http.StatusOK,res)
}
// Return failed
func (r *Result)Error(code int,msg string) {
res := ResultCont{}
res.Code = code
res.Msg = msg
res.Data = gin.H{}
r.Ctx.JSON(http.StatusOK,res)
r.Ctx.Abort()
}4,static/login.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title > title </title>
<meta charset="utf-8" />
<script type="text/javascript" language="JavaScript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<div id="content" style="width:800px;">
<div style="width:250px;float:left;font-size: 16px;" ></div>
<div style="width:550px;float:left;">
<!--====================main begin=====================-->
<input type="text" id="username" placeholder=" Please enter a user name " /><br/><br/>
<input type="password" id="password" placeholder=" Please input a password " /><br/><br/>
<input type="button" value=" Sign in " onclick="goLogin()"/>
<!--====================main end=====================-->
</div>
</div>
<script>
// visit 8080:/home/home
function goLogin(){
var postdata = {
username:document.getElementById("username").value,
password:document.getElementById("password").value,
}
$.ajax({
type:"POST",
url:"http://127.0.0.1:8080/user/login",
data:postdata,
// Return the format of the data
datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
// Base note function after successful return
success:function(data){
//alert(data);
if (data.code == 0){
alert(" Successful visit ");
} else {
alert(" error :"+data.msg);
}
},
// Base note
complete: function(XMLHttpRequest, textStatus){
},
// Call the function executed in error
error:function(jqXHR,textStatus,errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
</body>
</html>
Four , The test results
1, Sign in : visit :
http://127.0.0.1:8080/static/login.htmlEnter lhd/123 Click login later :

You can see after the login is successful ,session stay cookie End writes a id

2, Read session Content :
visit :
http://127.0.0.1:8080/user/sessionreturn :

3, Log out :
visit :
http://127.0.0.1:8080/user/logoutreturn :

Look again /usr/session page :

User session Has been cleared
5、 ... and , View the version of the library :
module github.com/liuhongdi/digv29
go 1.15
require (
github.com/gin-gonic/gin v1.6.3
github.com/gin-contrib/sessions v0.0.3
)
边栏推荐
- Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
- There is nothing new under the sun. Can the meta universe go higher?
- Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
- Road construction issues
- The solution of Chinese font garbled code in keil5
- [développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
- JS convert pseudo array to array
- The shadow of the object at the edge of the untiy world flickers, and the shadow of the object near the far point is normal
- Resource Cost Optimization Practice of R & D team
猜你喜欢

Unity EmbeddedBrowser浏览器插件事件通讯

NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
![[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update](/img/b8/31609303fd817c48b6fff7c43f31e5.png)
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
![[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心](/img/06/b71b505c7072d540955fda6da1dc1b.jpg)
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心

PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?

Logseq 评测:优点、缺点、评价、学习教程

Resolved (error in viewing data information in machine learning) attributeerror: target_ names

Golang — 命令行工具cobra

There is nothing new under the sun. Can the meta universe go higher?

Several common optimization methods matlab principle and depth analysis
随机推荐
Go language unit test 4: go language uses gomonkey to test functions or methods
When updating mysql, the condition is a query
Spark实战1:单节点本地模式搭建Spark运行环境
mysql更新时条件为一查询
Error running 'application' in idea running: the solution of command line is too long
IBEM 数学公式检测数据集
Anan's doubts
Go language unit test 3: go language uses gocovey library to do unit test
Resource Cost Optimization Practice of R & D team
Error handling when adding files to SVN:.... \conf\svnserve conf:12: Option expected
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
Kivy教程之 如何自动载入kv文件
Ocean CMS vulnerability - search php
Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
Mycms we media mall v3.4.1 release, user manual update
Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?
windos 创建cordova 提示 因为在此系统上禁止运行脚本
There is nothing new under the sun. Can the meta universe go higher?
IBEM mathematical formula detection data set
物联网毕设 --(STM32f407连接云平台检测数据)