当前位置:网站首页>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
)
边栏推荐
- Several common optimization methods matlab principle and depth analysis
- AI 考高数得分 81,网友:AI 模型也免不了“内卷”!
- [sort] bucket sort
- 编程内功之编程语言众多的原因
- 软件测试工作那么难找,只有外包offer,我该去么?
- Students who do not understand the code can also send their own token, which is easy to learn BSC
- Go language unit test 4: go language uses gomonkey to test functions or methods
- 挡不住了,国产芯片再度突进,部分环节已进到4nm
- Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
- 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
猜你喜欢

SQL Injection (GET/Search)

使用Tensorflow进行完整的深度神经网络CNN训练完成图片识别案例2

Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm

PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?

Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases

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

Tutoriel PowerPoint, comment enregistrer une présentation sous forme de vidéo dans Powerpoint?

Halcon combined with C # to detect surface defects -- Halcon routine autobahn

Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)

Resolved (error in viewing data information in machine learning) attributeerror: target_ names
随机推荐
php 迷宫游戏
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
Error handling when adding files to SVN:.... \conf\svnserve conf:12: Option expected
SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
Kivy教程之 如何通过字符串方式载入kv文件设计界面(教程含源码)
又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
TensorBoard可视化处理案例简析
Mycms we media mall v3.4.1 release, user manual update
Students who do not understand the code can also send their own token, which is easy to learn BSC
Kivy tutorial how to automatically load kV files
Unity embeddedbrowser browser plug-in event communication
JS 将伪数组转换成数组
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
Record 405 questions about bank callback post request
untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
掌握Cypress命令行选项,是真正掌握Cypress的基础
太阳底下无新事,元宇宙能否更上层楼?
Depth and breadth first traversal of tree (regardless of binary tree)
Can newly graduated European college students get an offer from a major Internet company in the United States?
Universal dividend source code, supports the dividend of any B on the BSC