当前位置:网站首页>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.html
Enter 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/session
return :
3, Log out :
visit :
http://127.0.0.1:8080/user/logout
return :
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
)
边栏推荐
- Screenshot of the operation steps of upload labs level 4-level 9
- 使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
- Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
- Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
- 【556. 下一个更大元素 III】
- [redis] cache warm-up, cache avalanche and cache breakdown
- 服务器硬盘冷迁移后网卡无法启动问题
- Asp.Net Core1.1版本没了project.json,这样来生成跨平台包
- mysql中的字段问题
- [quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
猜你喜欢
研发团队资源成本优化实践
MySQL 数据处理值增删改
Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
Students who do not understand the code can also send their own token, which is easy to learn BSC
使用Tensorflow进行完整的深度神经网络CNN训练完成图片识别案例2
[sort] bucket sort
Mastering the cypress command line options is the basis for truly mastering cypress
Universal dividend source code, supports the dividend of any B on the BSC
Kivy tutorial how to automatically load kV files
SQL Injection (GET/Select)
随机推荐
PhpMyAdmin stage file contains analysis traceability
Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
JS 将伪数组转换成数组
双向链表(我们只需要关注插入和删除函数)
树的深入和广度优先遍历(不考虑二叉树)
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Universal dividend source code, supports the dividend of any B on the BSC
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Introduction to the implementation principle of rxjs observable filter operator
Several common optimization methods matlab principle and depth analysis
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
SwiftUI 开发经验之作为一名程序员需要掌握的五个最有力的原则
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
太阳底下无新事,元宇宙能否更上层楼?
【被动收入如何挣个一百万】
Spark practice 1: build spark operation environment in single node local mode
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场