golang gin使用记录

github.com/gin-contrib/sessions教程

gitHub: https://github.com/gin-contrib/sessions

使用参考:https://blog.csdn.net/qq_16763983/article/details/105049118

Gin Mode的选择

1
gin.SetMode(gin.ReleaseMode)

gin框架提供了下列三种模式。这三种mode分别对应了不同的场景。在我们开发调试过程中,使用debug模式就可以了。在上线的时候,一定要选择release模式。而test可以用在测试场景中。

const (
// DebugMode indicates gin mode is debug.
DebugMode = “debug”
// ReleaseMode indicates gin mode is release.
ReleaseMode = “release”
// TestMode indicates gin mode is test.
TestMode = “test”
)

golang jwt+token验证

Go实战–golang中使用JWT(JSON Web Token)
Golang 实现JWT认证

gin框架中自定义向log中写入调试信息

How to write log file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func main() {
// Disable Console Color, you don't need console color when writing the logs to file.
gin.DisableConsoleColor()

// Logging to a file.
f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)

// Use the following code if you need to write the logs to file and console at the same time.
// gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})

   router.Run(":8080")
}

可以看到gin是通过DefaultWriter来确定日志写入的,查看代码(gin/mode.go中)如下:

1
2
3
4
5
6
7
8
9
// DefaultWriter is the default io.Writer used the Gin for debug output and
// middleware output like Logger() or Recovery().
// Note that both Logger and Recovery provides custom ways to configure their
// output io.Writer.
// To support coloring in Windows use:
// import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
var DefaultWriter io.Writer = os.Stdout
var DefaultErrorWriter io.Writer = os.Stderr

基于Token的身份验证的原理

参考:https://www.cnblogs.com/wnvalentin/articles/10816221.html

csrf token 生成与验证是如何做的呢?

  1. 服务器会在cookie中保存一个csrf_token_key, 用作钥匙。
  2. 服务器会在页面生成时,获取csrf_token_key这个钥匙, 生成一个随机的csrf_token令牌,当表单提交时,获取到csrf_token通过csrf_token_key解密比较是否一致。

Gin框架自定义解析json中的时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import (
"fmt"
"saasMigrateProject/go2cloud_platform/settings"

"time"
)

type Datetime time.Time

func (t Datetime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%v\"", time.Time(t).Format(settings.TimeFormat))
return []byte(stamp), nil
}

func (t *Datetime) UnmarshalJSON(data []byte) error {
timeStr := string(data)
if timeStr == "null" {
return nil
}
tm, err := time.Parse(settings.TimeFormat, timeStr)
*t = Datetime(tm)
return err
}

func (t Datetime) Value() time.Time {
return time.Time(t)
}

func (t Datetime) Now() Datetime {
return Datetime(time.Now())
}
-------------本文结束感谢您的阅读-------------