Moonlit Torii

FastGin Scaffold Development

FastGin scaffolding: initialization, CLI, routing, middleware, utilities, shared features, and deployment.

01 Developing the fastGin Scaffold

I have worked on several projects where each one had to be set up from scratch.

After doing this often enough, you start to notice that many parts are the same.

Initialization: read configuration files; connect to the database, Redis, logging, and other services.

Command-line operations: create databases and import or export data.

Routing: static routes and route groups.

Middleware: authentication and rate limiting.

JWT issuance: sign-in and sign-out.

Shared features: file uploads, image CAPTCHAs, and common list queries.

Deployment: Dockerfile and docker-compose configuration.

This introductory course explains each of these capabilities carefully.

For future projects that only need a simple permission model, this scaffold can serve as the starting point for further development.

I will make the course as detailed as possible, including the reasons for each design choice.

02 fastGin Scaffold: Initialization

Creating the Project

The first step is initialization.

Create a project; GoLand is commonly used for this.

Figure 1 for Creating the Project

Normally, you need to configure the GOPROXY environment variable.

Markdown
GOPROXY=https://goproxy.cn

This configures Go to use https://goproxy.cn as its proxy; it is a mirror hosted in China.

It makes future dependency downloads faster and more reliable.

You can also leave this field empty and set the environment variable directly.

Figure 2 for Creating the Project

Run go env; if GOPROXY is set to this URL, the configuration is correct.

If it is https://proxy.golang.org, change it with go env -w GOPROXY=https://goproxy.cn.

Configuration Files

Values that do not change often are usually stored in configuration files.

Examples include database addresses, user names and passwords, JWT expiration times, and file-upload paths.

Without a configuration file, changing any of these settings requires recompiling the program.

This project uses YAML configuration files.

TOML, INI, and JSON are also fine; you only need to parse the chosen format in Go.

YAML is more flexible, simple to use, and supports comments.

You only need a basic grasp of YAML syntax—enough to write simple configuration.

Figure 1 for Configuration Files

Put a space between a colon and the value that follows it.

YAML
name: 字符串
name1: '字符串'
name2: "字符串" # 这三种字符串都可以
age: 21
isGender: true
isGender1: True  # 两种bool都可以
arr1: [1,2,3]
arr2:
  - 1
  - 2
  - 3 # 两种数组都可以
obj2:
  name: fengfeng
  age: 12

Parsing a YAML file

The library used here is gopkg.in/yaml.v3.

Go
byteData, _ := os.ReadFile("settings.yaml")
var data map[string]any
err := yaml.Unmarshal(byteData, &data)
if err != nil {
  fmt.Println(err)
  return
}
fmt.Println(data)

This example uses a map to receive the data, but you can replace it with another type, such as a matching struct.

Further Notes on Configuration

Here is a related point to consider.

At the moment, after changing the configuration file, the application must be restarted before it can use the new values.

Is there a way to change configuration dynamically without restarting the container?

There are two approaches.

The first is to store it directly in memory.

The second is to introduce a configuration center and retrieve configuration through an API, such as etcd or Nacos.

Logging Configuration

Logging is extremely important.

I strongly recommend writing plenty of logs while developing a project.

Problems are inevitable in software development; that is completely normal.

What matters is whether the logs let you identify where a problem occurred,

rather than having to inspect the code only after an issue appears and infer the cause.

This also raises the question of whether backend error details should be returned to the frontend.

The answer depends on the situation. For an internal company application, returning the error directly is fine: when an error occurs, its cause is immediately clear and can be fixed.

For an external product, returning raw backend errors looks unpolished. Wrap them in consistent messages such as network or system errors, while recording the detailed error in the logs.

This example uses logrus, though you can choose zap instead.

Go
go get github.com/sirupsen/logrus

In general, a log entry should show where it was written and when.

There are also advanced features such as log rotation by time, size, or log level.

  1. Configure a formatter

Implement the Format(entry *logrus.Entry) ([]byte, error) method.

Go
type MyLog struct {
}

// 颜色
const (
  red    = 31
  yellow = 33
  blue   = 36
  gray   = 37
)

func (MyLog) Format(entry *logrus.Entry) ([]byte, error) {
  //根据不同的level去展示颜色
  var levelColor int
  switch entry.Level {
  case logrus.DebugLevel, logrus.TraceLevel:
    levelColor = gray
  case logrus.WarnLevel:
    levelColor = yellow
  case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
    levelColor = red
  default:
    levelColor = blue
  }
  var b *bytes.Buffer
  if entry.Buffer != nil {
    b = entry.Buffer
  } else {
    b = &bytes.Buffer{}
  }
  //自定义日期格式
  timestamp := entry.Time.Format("2006-01-02 15:04:05")
  if entry.HasCaller() {
    //自定义文件路径
    funcVal := entry.Caller.Function
    fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
    //自定义输出格式
    fmt.Fprintf(b, "[%s] \x1b[%dm[%s]\x1b[0m %s %s %s\n", timestamp, levelColor, entry.Level, fileVal, funcVal, entry.Message)
  }
  return b.Bytes(), nil
}
  1. Configure a hook

After a log entry is produced, the hook writes it to a log file.

Rotate logs by day.

Store error logs separately.

Go
type MyHook struct {
  file     *os.File
  errFile  *os.File
  fileDate string
  logPath  string
  mu       sync.Mutex
}

func (hook *MyHook) Fire(entry *logrus.Entry) error {
  hook.mu.Lock()
  defer hook.mu.Unlock()

  timer := entry.Time.Format("2006-01-02")
  line, err := entry.String()
  if err != nil {
    return fmt.Errorf("failed to format log entry: %v", err)
  }

  if hook.fileDate != timer {
    if err := hook.rotateFiles(timer); err != nil {
      return err
    }
  }

  if _, err := hook.file.Write([]byte(line)); err != nil {
    return fmt.Errorf("failed to write to log file: %v", err)
  }

  if entry.Level <= logrus.ErrorLevel {
    if _, err := hook.errFile.Write([]byte(line)); err != nil {
      return fmt.Errorf("failed to write to error log file: %v", err)
    }
  }

  return nil
}

// rotateFiles 日志轮换
func (hook *MyHook) rotateFiles(timer string) error {
  if hook.file != nil {
    if err := hook.file.Close(); err != nil {
      return fmt.Errorf("failed to close log file: %v", err)
    }
  }
  if hook.errFile != nil {
    if err := hook.errFile.Close(); err != nil {
      return fmt.Errorf("failed to close error log file: %v", err)
    }
  }

  dirName := fmt.Sprintf("%s/%s", hook.logPath, timer)
  if err := os.MkdirAll(dirName, os.ModePerm); err != nil {
    return fmt.Errorf("failed to create log directory: %v", err)
  }

  infoFilename := fmt.Sprintf("%s/info.log", dirName)
  errFilename := fmt.Sprintf("%s/err.log", dirName)

  var err error
  hook.file, err = os.OpenFile(infoFilename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  if err != nil {
    return fmt.Errorf("failed to open log file: %v", err)
  }

  hook.errFile, err = os.OpenFile(errFilename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  if err != nil {
    return fmt.Errorf("failed to open error log file: %v", err)
  }

  hook.fileDate = timer
  return nil
}

// Levels 哪些级别的日志能走 Fire 方法
func (hook *MyHook) Levels() []logrus.Level {
  return logrus.AllLevels
}

Database Connection

Three databases and four connection modes are supported.

https://gorm.io/zh_CN/docs/connecting_to_the_database.html#MySQL

  1. MySQL

  2. PostgreSQL

  3. SQLite via github.com/glebarez/sqlite

    Using the default gorm.io/driver/sqlite here will probably trigger

    [error] failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub panic: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub

    This happens because GORM's SQLite driver uses CGO and therefore requires a CGO-enabled environment.

    Reference: https://www.jb51.net/jiaoben/3147895tu.htm

  4. No connection

Configuration file

YAML
db:
  mode: mysql # mysql pgsql sqlite ""
  db_name: ""
  host: ""
  port: 3306
  user: ""
  password: ""

Use a simple factory pattern to initialize a different GORM database connection for each mode.

Go
package core

import (
  "fmt"
  "github.com/glebarez/sqlite"
  "github.com/sirupsen/logrus"
  "gorm.io/driver/mysql"
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
  "time"
)

type DB struct {
  Mode     string `yaml:"mode"`
  DbName   string `yaml:"db_name"`
  Host     string `yaml:"host"`
  Port     int    `yaml:"port"`
  User     string `yaml:"user"`
  Password string `yaml:"password"`
}

func InitGorm() (database *gorm.DB) {
  var db DB
  var dialector gorm.Dialector
  switch db.Mode {
  case "mysql":
    dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
      db.User,
      db.Password,
      db.Host,
      db.Port,
      db.DbName,
    )
    dialector = mysql.Open(dsn)
  case "pgsql":
    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
      db.Host,
      db.User,
      db.Password,
      db.DbName,
      db.Port,
    )
    dialector = postgres.Open(dsn)
  case "sqlite":
    dialector = sqlite.Open(db.Host)
  case "":
    logrus.Warnf("未配置数据库连接")
    return nil
  default:
    logrus.Fatalf("不支持的数据库mode配置")
  }
  database, err := gorm.Open(dialector, &gorm.Config{
    DisableForeignKeyConstraintWhenMigrating: true, // 不生成实体外键
  })
  if err != nil {
    logrus.Fatalf("数据库连接失败 %s", err)
    return
  }
  // 配置连接池
  sqlDB, err := database.DB()
  if err != nil {
    logrus.Fatalf("获取数据库连接失败 %s", err)
    return
  }
  err = sqlDB.Ping()
  if err != nil {
    logrus.Fatalf("数据库连接失败 %s", err)
    return
  }
  // 设置连接池
  sqlDB.SetMaxIdleConns(10)
  sqlDB.SetMaxOpenConns(100)
  sqlDB.SetConnMaxLifetime(time.Hour)
  return
}

Normally, if a project has no database or cannot connect to one, there is no reason to continue starting it.

However, to make it easier to run this project with minimal setup, connecting to a database is optional.

When using the database later, check whether db is nil; otherwise, you may encounter a null-pointer error.

Redis Connection

There is not much to cover here; the setup is straightforward.

Go
package core

import (
  "context"
  "github.com/redis/go-redis/v9"
  "github.com/sirupsen/logrus"
)

type Conf struct {
  Addr     string
  Password string
  DB       int
}

func InitRedis() {
  var conf Conf
  rdb := redis.NewClient(&redis.Options{
    Addr:     conf.Addr,
    Password: conf.Password,
    DB:       conf.DB,
  })

  _, err := rdb.Ping(context.Background()).Result()
  if err != nil {
    logrus.Errorf("连接redis失败 %s", err)
    return
  }
  logrus.Infof("成功连接redis")
}

03 fastGin Scaffold: Command-line Operations

Go
package flags

import (
  "fast_gin/global"
  "flag"
  "fmt"
)

type FlagOptions struct {
  File    string
  Version bool
  DB      bool
}

var Options FlagOptions

func Parse() {
  flag.StringVar(&Options.File, "f", "settings.yaml", "配置文件路径")
  flag.BoolVar(&Options.Version, "v", false, "打印当前版本")
  flag.BoolVar(&Options.DB, "db", false, "迁移表结构")
  flag.Parse()
}

func Run() (ok bool) {
  if Options.DB {
    fmt.Println("表结构迁移")
    return true
  }
  if Options.Version {
    fmt.Println("当前后端版本", global.Version)
    return true
  }
  return false
}


Use Go's built-in flag package to bind command-line arguments.

Run go run main.go -h to view all bound arguments.

Figure 1 for 03 fastGin Scaffold: Command-line Operations

We also need the program to stop after executing -v or -db.

This is simple: keep Parse and Run separate.

Go
package main

import (
  "fast_gin/core"
  "fast_gin/flags"
  "fast_gin/global"
  "fmt"
)

func main() {
  core.InitLogger()
  flags.Parse()
  global.Config = core.ReadConfig()
  global.DB = core.InitGorm()
  global.Redis = core.InitRedis()

  if flags.Run() {
    return
  }

  fmt.Println("web服务")
}

Sometimes you need to know which version is running in the production environment.

Use a command-line option to retrieve it.

Go
func Run() (ok bool) {
  if Options.Version {
    fmt.Println("当前后端版本", global.Version)
    return true
  }
  return false
}

Migrate the Database Schema

Go

func Run() {
  if Options.DB {
    MigrateDB()
    os.Exit(0)
  }
  if Options.Version {
    fmt.Println("当前后端版本", global.Version)
    os.Exit(0)
  }
}


Schema definition

Go
type UserModel struct {
  Model
  Username string `gorm:"size:16" json:"username"`
  Nickname string `gorm:"size:32" json:"nickname"`
  Password string `gorm:"size:64" json:"password"`
  RoleID   int8   `json:"roleID"` // 1 管理员 2 普通用户
}

Go
func MigrateDB() {
  err := global.DB.AutoMigrate(&models.UserModel{})
  if err != nil {
    logrus.Errorf("表结构迁移失败 %s", err)
    return
  }
  logrus.Infof("表结构迁移成功")
}

Create a User

Create users from the command line.

Go
package flags

import (
  "fast_gin/global"
  "fast_gin/models"
  "fast_gin/utils/pwd"
  "fmt"
  "github.com/sirupsen/logrus"
  "golang.org/x/crypto/ssh/terminal"
  "os"
)

type User struct {
}

func (User) Create() {
  var user models.UserModel
  fmt.Println("请选择角色: 1 管理员 2 普通用户")
  _, err := fmt.Scanln(&user.RoleID)
  if err != nil {
    fmt.Println("输入错误", err)
    return
  }
  if user.RoleID != 1 && user.RoleID != 2 {
    fmt.Println("用户角色输入错误", err)
    return
  }
  fmt.Println("请输入用户名")
  fmt.Scanln(&user.Username)

  var u models.UserModel
  err = global.DB.Take(&u, "username = ?", user.Username).Error
  if err == nil {
    fmt.Println("用户名已存在")
    return
  }

  fmt.Println("请输入密码")
  password, err := terminal.ReadPassword(int(os.Stdin.Fd())) // 读取用户输入的密码
  if err != nil {
    fmt.Println("读取密码时出错:", err)
    return
  }
  fmt.Println("请再次输入密码")
  rePassword, err := terminal.ReadPassword(int(os.Stdin.Fd())) // 读取用户输入的密码
  if err != nil {
    fmt.Println("读取密码时出错:", err)
    return
  }
  if string(password) != string(rePassword) {
    fmt.Println("两次密码不一致")
    return
  }

  hashPwd := pwd.GenerateFromPassword(string(password))
  err = global.DB.Create(&models.UserModel{
    Username: user.Username,
    Password: hashPwd,
    RoleID:   user.RoleID,
  }).Error
  if err != nil {
    logrus.Errorf("用户创建失败 %s", err)
    return
  }
  logrus.Infof("用户创建成功")

}
func (User) List() {
  var userList []models.UserModel
  global.DB.Order("created_at desc").Limit(10).Find(&userList)
  for _, model := range userList {
    fmt.Printf("用户id:%d  用户名:%s 用户昵称:%s 用户角色:%d 创建时间:%s\n",
      model.ID,
      model.Username,
      model.Nickname,
      model.RoleID,
      model.CreatedAt.Format("2006-01-02 15:04:05"),
    )
  }
}

04 fastGin Scaffold: Routing

Go
package routers

import (
  "github.com/gin-gonic/gin"
)

func UserRouter(r *gin.RouterGroup) {
  r.GET("users", func(c *gin.Context) {
    c.String(200, "users")
  })
}

func Run() {
  // 设置模式
  gin.SetMode("release")

  r := gin.Default()

  // 静态路由
  r.Static("/uploads", "uploads")

  // 路由分组
  api := r.Group("api")
  UserRouter(api)

  r.Run(":8080")
}


Static Routes

Map a URL route directly to a directory.

Go
r.Static("/uploads", "uploads")

You can also map an individual file.

Go
r.StaticFile("/xxx/a.txt", "uploads/a.txt")

Route Groups

Route groups are typically used to organize related endpoints and make it easy to add middleware to the entire group.

Go
func UserRouter(g *gin.RouterGroup) {
  r := g.Group("users").Use() // 可以方便的加中间件

  r.GET("", func(c *gin.Context) {
    c.String(200, "user list")
  })
  r.POST("", func(c *gin.Context) {
    c.String(200, "user add")
  })
  r.DELETE("", func(c *gin.Context) {
    c.String(200, "user remove")
  })
}

05 fastGin Scaffold: Middleware

Middleware is at the heart of a web system. Used well, it can deliver much more with much less effort.

Authentication Middleware

Issue a token through the sign-in endpoint.

When calling an endpoint that requires authentication, put the token in the request header. The middleware verifies that it is valid and has not expired.

Invalid requests are intercepted before reaching the handler layer; valid requests proceed to it.

Go
package middleware

import (
  "fast_gin/utils/jwts"
  "github.com/gin-gonic/gin"
)

func AuthMiddleware(c *gin.Context) {
  token := c.GetHeader("token")
  _, err := jwts.CheckToken(token)
  if err != nil {
    c.JSON(200, gin.H{"code": 7, "msg": "认证失败", "data": gin.H{}})
    c.Abort()
    return
  }
  c.Next()
}

func AdminMiddleware(c *gin.Context) {
  token := c.GetHeader("token")
  claims, err := jwts.CheckToken(token)
  if err != nil {
    c.JSON(200, gin.H{"code": 7, "msg": "认证失败", "data": gin.H{}})
    c.Abort()
    return
  }
  if claims.RoleID != 1 {
    c.JSON(200, gin.H{"code": 7, "msg": "角色认证失败", "data": gin.H{}})
    c.Abort()
    return
  }
  c.Next()
}

Rate-limiting Middleware

Why rate limit?

If you have visited a tourist attraction, you will know that reservations are often required to control visitor flow.

There are many rate-limiting strategies:

https://blog.csdn.net/YouMing_Li/article/details/141787087

IP-based rate limiting

https://www.jb51.net/article/281431.htm

Go
package middleware

import (
  "github.com/gin-gonic/gin"
  "time"
)

func LimitMiddleware(limit int) gin.HandlerFunc {
  return NewLimiter(limit, 1*time.Second).Middleware
}

// NewLimiter 创建限流器
func NewLimiter(limit int, duration time.Duration) *Limiter {
  return &Limiter{
    limit:      limit,
    duration:   duration,
    timestamps: make(map[string][]int64),
  }
}

// Limiter 限流器
type Limiter struct {
  limit      int                // 限制的请求数量
  duration   time.Duration      // 时间窗口
  timestamps map[string][]int64 // 请求的时间戳
}

// Middleware 限流中间件
func (l *Limiter) Middleware(c *gin.Context) {
  ip := c.ClientIP() // 获取客户端IP地址

  // 检查请求时间戳切片是否存在
  if _, ok := l.timestamps[ip]; !ok {
    l.timestamps[ip] = make([]int64, 0)
  }

  now := time.Now().Unix() // 当前时间戳

  // 移除过期的请求时间戳
  for i := 0; i < len(l.timestamps[ip]); i++ {
    if l.timestamps[ip][i] < now-int64(l.duration.Seconds()) {
      l.timestamps[ip] = append(l.timestamps[ip][:i], l.timestamps[ip][i+1:]...)
      i--
    }
  }

  // 检查请求数量是否超过限制
  if len(l.timestamps[ip]) >= l.limit {
    c.JSON(429, gin.H{
      "code": 9,
      "data": gin.H{},
      "msg":  "Too Many Requests",
    })
    c.Abort()
    return
  }

  // 添加当前请求时间戳到切片
  l.timestamps[ip] = append(l.timestamps[ip], now)

  // 继续处理请求
  c.Next()
}

Parameter-binding Middleware

First, look at how parameter binding was handled previously.

All parameter binding occurred in the handler layer.

Go
type LoginRequest struct {
  Username string `json:"username" binding:"required" label:"用户名"`
  Password string `json:"password" binding:"required" label:"密码"`
}

func (UserApi) LoginView(c *gin.Context) {
  var cr LoginRequest
  err := c.ShouldBindJSON(&cr)
  if err != nil {
    res.FailWithError(err, c)
    return
  }
  fmt.Println(cr)
  res.OkWithData("用户登录", c)
  return
}

You will notice that the binding steps are always the same; only the target struct type differs.

We can therefore write a generic function for parameter binding.

Go
func BindJson[T any](c *gin.Context) (cr T, err error) {
  err = c.ShouldBindJSON(&cr)
  if err != nil {
    res.FailWithError(err, c)
    return
  }
  return
}

func (UserApi) LoginView(c *gin.Context) {
  cr, err := BindJson[LoginRequest](c)
  if err != nil {
    return
  }
  fmt.Println(cr)
  res.OkWithData("用户登录", c)
  return
}

The original six lines become four, but the error check is still necessary.

How can we extract that error handling as well?

We can build on middleware.

If middleware performs the binding, returns immediately on failure, and only proceeds after success, the handler function is guaranteed to receive bound parameters.

Go
package middleware

import (
  "fast_gin/utils/res"
  "github.com/gin-gonic/gin"
)

func BindJsonMiddleware[T any](c *gin.Context) {
  var cr T
  err := c.ShouldBindJSON(&cr)
  if err != nil {
    res.FailWithError(err, c)
    c.Abort()
    return
  }
  c.Set("request", cr)
  return
}

func BindQueryMiddleware[T any](c *gin.Context) {
  var cr T
  err := c.ShouldBindQuery(&cr)
  if err != nil {
    res.FailWithError(err, c)
    c.Abort()
    return
  }
  c.Set("request", cr)
  return
}
func BindUriMiddleware[T any](c *gin.Context) {
  var cr T
  err := c.ShouldBindUri(&cr)
  if err != nil {
    res.FailWithError(err, c)
    c.Abort()
    return
  }
  c.Set("request", cr)
  return
}

func GetBind[T any](c *gin.Context) (cr T) {
  return c.MustGet("request").(T)
}

Use it in a route

Go
g.POST("users/login", middleware.LimitMiddleware(2), middleware.BindJsonMiddleware[user_api.LoginRequest], app.LoginView)

Use it in a handler

Go
type LoginRequest struct {
  Username string `json:"username" binding:"required" label:"用户名"`
  Password string `json:"password" binding:"required" label:"密码"`
}

func (UserApi) LoginView(c *gin.Context) {
  cr := middleware.GetBind[LoginRequest](c)
  fmt.Println(cr)
  res.OkWithData("用户登录", c)
  return
}

06 fastGin Scaffold: Utilities

Password Hashing

This is Go's built-in password-hashing library.

Compared with traditional MD5, bcrypt is more secure.

Go
import "golang.org/x/crypto/bcrypt"

// GenerateFromPassword 加密密码
func GenerateFromPassword(password string) (string, error) {
  hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  if err != nil {
    return "", err
  }
  return string(hashedPassword), nil
}

// CompareHashAndPassword 校验密码
func CompareHashAndPassword(hashedPassword string, password string) bool {
  err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
  return err == nil
}

JWT Issuance and Verification

A JWT consists of three parts:

Go
头部.载荷.签名

JWTs do not encrypt their payload, so do not put sensitive data in it.

  1. Call the sign-in endpoint. The backend generates and returns a JWT whose payload contains required information, such as the user ID and permission ID.
  2. The frontend persists the token, then includes it in later request headers.
  3. When a user calls an endpoint that requires authentication, the backend checks whether the token is valid and unexpired. Authentication succeeds only when both conditions are met.

How do we determine whether a token is valid—how do we know it has not been tampered with?

The key is the signature. The algorithm defined in the header is used to sign the header and payload together with a private key.

Signing process

JSON
{sha256}.{userID:1,role:2}.xxxx
cecret: 1234

xxxx: sha256(base46Encode({sha256}.{userID:1,role:2}))


Verification process:

JavaScript
sdgk.djerjretj.xxxx
可以拿到头部的加密方式 是 sha256
我们再加密一次
yyyy = sha256(sdgk.djerjretj)
只需要判断 yyyy是不是等于xxxx 如果相等,就说明jwt没有被篡改
如果不等就说明被篡改了


JWT limitation:

  1. It has no active-expiration strategy.

How to Expire a JWT

  1. Token blacklist strategy

When a user signs out, put the token in Redis.

During authentication, first check whether the token was tampered with or has expired, then check whether it is in Redis's blacklist.

If it is blacklisted, that token was previously signed out and authentication must fail.

JWT Dual-token Pattern

JSON Web Tokens are commonly used for identity authentication in separated frontend and backend architectures.

JWTs support a single-token pattern and a dual-token pattern.

In the single-token pattern, the server generates only one token. Its expiration is generally long, so security is somewhat weaker.

In the dual-token pattern, the server generates two tokens: an access_token for authorization with a short lifetime (such as 5 or 15 minutes), and a refresh_token used only to obtain a new access_token, with a longer lifetime (for example, 24 hours or more).

Typical single-token flow:

  1. The frontend submits a sign-in request.
  2. The server verifies the user name and password, then returns a token.
  3. The frontend stores the returned token.
  4. Later frontend requests carry the token in the request header for server-side verification.
  5. The server verifies the token before providing the service; otherwise, it returns an appropriate message.

Typical dual-token flow:

  1. The frontend submits a sign-in request.
  2. The server verifies the user name and password, then returns an access_token and refresh_token.
  3. The frontend stores both returned tokens.
  4. Later frontend requests carry the access_token for server-side verification.
  5. The server verifies the token before providing the service; otherwise, it returns an appropriate message.
  6. After the access_token expires, the frontend replaces it in the request header with the refresh_token and calls the refresh endpoint. It stores the new access_token and retries the request. The refresh_token can obtain an access_token only; it cannot authorize other endpoints.

Generate a JWT in Go

Go
// utils/jwts/enter.go
package jwts

import (
  "errors"
  "fai_server/global"
  "github.com/dgrijalva/jwt-go"
  "time"
)

type ClaimsUserInfo struct {
  UserID uint `json:"userID"`
  Role   int8 `json:"role"`
}

type Claims struct {
  ClaimsUserInfo
  jwt.StandardClaims
}

// GetToken 生成token
func GetToken(info ClaimsUserInfo) (string, error) {
  j := global.Config.Jwt
  cla := Claims{
    ClaimsUserInfo: info,
    StandardClaims: jwt.StandardClaims{
      ExpiresAt: time.Now().Add(time.Duration(j.Expires) * time.Hour).Unix(), // 过期时间
      Issuer:    j.Issuer,                                                    // 签发人
    },
  }
  token := jwt.NewWithClaims(jwt.SigningMethodHS256, cla)
  return token.SignedString([]byte(j.Secret)) // 进行签名生成对应的token
}

// ParseToken 解析token
func ParseToken(tokenString string) (*Claims, error) {
  j := global.Config.Jwt
  token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
    return []byte(j.Secret), nil
  })
  if err != nil {
    return nil, err
  }
  claims, ok := token.Claims.(*Claims)
  if ok && token.Valid {
    if claims.Issuer != j.Issuer {
      return nil, errors.New("invalid issuer")
    }
    return claims, nil
  }
  return nil, errors.New("invalid token")
}

Response Wrappers

Go
package res

import "github.com/gin-gonic/gin"

type Response struct {
  Code int    `json:"code"`
  Data any    `json:"data"`
  Msg  string `json:"msg"`
}

func Ok(data any, msg string, c *gin.Context) {
  c.JSON(200, Response{
    Code: 0,
    Data: data,
    Msg:  msg,
  })
}

func OkWithMsg(msg string, c *gin.Context) {
  Ok(gin.H{}, msg, c)
}
func OkWithData(data any, c *gin.Context) {
  Ok(data, "成功", c)
}

func Fail(code int, msg string, c *gin.Context) {
  c.JSON(200, Response{
    Code: code,
    Data: gin.H{},
    Msg:  msg,
  })
}

func FailWithMsg(msg string, c *gin.Context) {
  Fail(7, msg, c)
}

func FailWithError(err error, c *gin.Context) {
  Fail(7, err.Error(), c)
}

Calculate MD5

Although MD5 is unsafe for passwords, it can still be used for other verification tasks,

such as checking file integrity.

Go
package md5

import (
  "crypto/md5"
  "encoding/hex"
  "io"
  "mime/multipart"
)

func MD5WithFile(file multipart.File) string {
  m := md5.New()
  io.Copy(m, file)
  hashBytes := m.Sum(nil)
  return hex.EncodeToString(hashBytes)
}

07 fastGin Scaffold: Shared Features

Image Uploads

  1. Size limits
  2. An allowlist
  3. Duplicate filename handling
Go
package image_api

import (
  "fast_gin/global"
  "fast_gin/utils/find"
  "fast_gin/utils/md5"
  "fast_gin/utils/random"
  "fast_gin/utils/res"
  "fmt"
  "github.com/gin-gonic/gin"
  "os"
  "path"
  "path/filepath"
  "strings"
)

var whiteList = []string{
  ".jpg",
  ".jpeg",
  ".png",
  ".webp",
}

func (ImageApi) UploadView(c *gin.Context) {
  fileHeader, err := c.FormFile("file")
  if err != nil {
    res.FailWithMsg("请选择文件", c)
    return
  }

  // 大小限制
  if fileHeader.Size > global.Config.Upload.Size*1024*1024 {
    res.FailWithMsg("上传文件过大", c)
    return
  }
  // 后缀判断
  ext := strings.ToLower(filepath.Ext(fileHeader.Filename))

  if !find.InList(whiteList, ext) {
    res.FailWithMsg("上传文件后缀非法", c)
    return
  }

  // 处理文件名重复
  // uploads/images/xx.jpg
  // uploads/images/xx_7hf.jpg
  fp := path.Join("uploads", global.Config.Upload.Dir, fileHeader.Filename)
  for {
    _, err1 := os.Stat(fp)
    if os.IsNotExist(err1) {
      break
    }
    // 文件存在
    // 算上传的图片和本身的图片是不是一样的,如果是一样的,那就直接返回之前的地址
    uploadFile, _ := fileHeader.Open()
    oldFile, _ := os.Open(fp)

    uploadFileHash := md5.MD5WithFile(uploadFile)
    oldFileHash := md5.MD5WithFile(oldFile)
    if uploadFileHash == oldFileHash {
      // 上传的图片,名称和内容都是一样的
      res.Ok("/"+fp, "上传成功", c)
      return
    }
    // 上传的图片,名称是一样的,但是内容不一样
    fileNameNotExt := strings.TrimSuffix(fileHeader.Filename, ext)
    newFileName := fmt.Sprintf("%s_%s%s", fileNameNotExt, random.RandStr(3), ext)
    fp = path.Join("uploads", global.Config.Upload.Dir, newFileName)
  }
  c.SaveUploadedFile(fileHeader, fp)

  res.Ok("/"+fp, "上传成功", c)
}


Generate an Image CAPTCHA

You can use this third-party library:

https://github.com/mojocn/base64Captcha?tab=readme-ov-file

The important part is the verification flow that follows image-CAPTCHA generation.

Generating an image CAPTCHA returns a random string and the image's Base64 encoding.

The backend stores the correct CAPTCHA value for that random string in memory.

The frontend renders the image. When verification is needed, it sends the user-entered CAPTCHA and the random string to the backend.

The backend uses the random string to check whether the CAPTCHA is correct.

Go
package captcha_api

import (
  "fast_gin/utils/captcha"
  "fast_gin/utils/res"
  "github.com/gin-gonic/gin"
  "github.com/mojocn/base64Captcha"
  "github.com/sirupsen/logrus"
)

type GenerateResponse struct {
  CaptchaID string `json:"captchaID"`
  Captcha   string `json:"captcha"`
}

func (CaptchaApi) GenerateView(c *gin.Context) {
  var driver = base64Captcha.DriverString{
    Width:           200,
    Height:          60,
    NoiseCount:      2,
    ShowLineOptions: 4,
    Length:          4,
    Source:          "0123456789",
  }
  cp := base64Captcha.NewCaptcha(&driver, captcha.CaptchaStore)
  id, b64s, _, err := cp.Generate()
  if err != nil {
    logrus.Errorf("图片验证码生成失败 %s", err)
    res.FailWithMsg("图片验证码生成失败", c)
    return
  }
  res.OkWithData(GenerateResponse{
    CaptchaID: id,
    Captcha:   b64s,
  }, c)
}

Display a Base64 Image in Apifox

TypeScript

//pm是apifox的内置对象,通过这个对象,可以获取到请求结果(response)
//通过.json()函数,获取到响应体中返回的json数据
let res = pm.response.json()

//定义一个模板,这个模板存的是
const template = `<html><img src="{{imgTemplate}}" /></html>`;

//构建img标签能识别的base64 url,注:如果接口返回的base64 url没有【data:image/png;base64,】则需要拼接进去,否则出不来图片。
//因接口返回的是一个数组,这里打印打一张图片
let img= res.data.captcha;
//console.log(img) //打印

// 设置 visualizer 数据。
//template:模板,上面const定义的template。
// {imgTemplate: img},imgTemplate对应的是template中src的值;img指的是上述定义的img base64 url
pm.visualizer.set(template, {
    imgTemplate: img
})


Sign In and Sign Out

Verify the user name and password, then issue a token.

Go
package user_api

import (
  "fast_gin/global"
  "fast_gin/middleware"
  "fast_gin/models"
  "fast_gin/utils/captcha"
  "fast_gin/utils/jwts"
  "fast_gin/utils/pwd"
  "fast_gin/utils/res"
  "github.com/gin-gonic/gin"
  "github.com/sirupsen/logrus"
)

type LoginRequest struct {
  Username    string `json:"username" binding:"required" label:"用户名"`
  Password    string `json:"password" binding:"required" label:"密码"`
  CaptchaID   string `json:"captchaID"`
  CaptchaCode string `json:"captchaCode"`
}

func (UserApi) LoginView(c *gin.Context) {
  cr := middleware.GetBind[LoginRequest](c)

  if global.Config.Site.Login.Captcha {
    if cr.CaptchaID == "" || cr.CaptchaCode == "" {
      res.FailWithMsg("请输入图片验证码", c)
      return
    }
    if !captcha.CaptchaStore.Verify(cr.CaptchaID, cr.CaptchaCode, true) {
      res.FailWithMsg("图片验证码验证失败", c)
      return
    }
  }

  var user models.UserModel
  err := global.DB.Take(&user, "username = ?", cr.Username).Error
  if err != nil {
    res.FailWithMsg("用户名或密码错误", c)
    return
  }

  if !pwd.CompareHashAndPassword(user.Password, cr.Password) {
    res.FailWithMsg("用户名或密码错误", c)
    return
  }

  token, err := jwts.SetToken(jwts.Claims{
    UserID: user.ID,
    RoleID: user.RoleID,
  })
  if err != nil {
    logrus.Errorf("生成token失败 %s", err)
    res.FailWithMsg("登录失败", c)
    return
  }

  res.OkWithData(token, c)
  return
}

Sign out

Put the token in the Redis blacklist and set its expiration to the token's expiry time.

Go
package redis_ser

import (
  "context"
  "fast_gin/global"
  "fast_gin/utils/jwts"
  "fmt"
  "github.com/sirupsen/logrus"
  "time"
)

func Logout(token string) {
  claims, err := jwts.CheckToken(token)
  if err != nil {
    return
  }
  key := fmt.Sprintf("logout_%s", token)
  sub := claims.ExpiresAt.Sub(time.Now())

  _, err = global.Redis.Set(context.Background(), key, "", sub).Result()
  if err != nil {
    logrus.Error(err)
  }
}

func HasLogout(token string) (ok bool) {
  key := fmt.Sprintf("logout_%s", token)
  _, err := global.Redis.Get(context.Background(), key).Result()
  if err == nil {
    return true
  }
  return false
}

User List

  1. Paginated queries
  2. Fuzzy matching
  3. Keyword queries
Go
package user_api

import (
  "fast_gin/global"
  "fast_gin/middleware"
  "fast_gin/models"
  "fast_gin/utils/res"
  "github.com/gin-gonic/gin"
)

func (UserApi) UserListView(c *gin.Context) {
  var cr = middleware.GetBind[models.PageInfo](c)
  var list = make([]models.UserModel, 0)
  query := global.DB.Where("")

  if cr.Key != "" {
    query.Where("username like ?", "%"+cr.Key+"%")
  }

  offset := (cr.Page - 1) * cr.Limit

  global.DB.Where(query).Limit(cr.Limit).Offset(offset).Order(cr.Order).Find(&list)

  var count int64
  global.DB.Where(query).Count(&count)

  res.OkWithList(list, count, c)
}

Generic List Queries

Go
package common

import (
  "fast_gin/global"
  "fast_gin/models"
  "fmt"
  "gorm.io/gorm"
)

type QueryOption struct {
  models.PageInfo
  Likes    []string
  Where    *gorm.DB
  Preloads []string
  Debug    bool
}

func QueryList[T any](model T, option QueryOption) (list []T, count int64, err error) {
  list = make([]T, 0)
  // 自己身上的
  query := global.DB.Where(model)

  // 模糊匹配
  if option.Key != "" {
    if len(option.Likes) != 0 {
      likeQuery := global.DB.Where("")
      for _, column := range option.Likes {
        likeQuery.Or(fmt.Sprintf("%s like ?", column), fmt.Sprintf("%%%s%%", option.Key))
      }
      query.Where(likeQuery)
    }
  }

  // 预加载
  for _, preload := range option.Preloads {
    query = query.Preload(preload)
  }

  // 分页
  if option.Page <= 0 {
    option.Page = 1
  }
  if option.Limit <= 0 {
    option.Limit = -1
  }

  offset := (option.Page - 1) * option.Limit

  if option.Order == "" {
    option.Order = "created_at desc"
  }

  db := global.DB.Where("")
  if option.Debug {
    db = db.Debug()
  }

  db.Where(query).Limit(option.Limit).Offset(offset).Order(option.Order).Find(&list)
  db.Model(model).Where(query).Count(&count)
  return
}

How to use it

Go
func (UserApi) UserListView(c *gin.Context) {
  var cr = middleware.GetBind[models.PageInfo](c)

  list, count, _ := common.QueryList(models.UserModel{}, common.QueryOption{
    PageInfo: cr,
    Likes:    []string{"username", "nickname"},
    Debug:    true,
  })
  res.OkWithList(list, count, c)
}

08 fastGin Scaffold: Project Deployment

Originally, my workflow was local development, cross-compilation, uploading the executable, and then managing the process with Supervisor on the server.

Now, Go projects are often deployed directly with Docker.

First, learn how to pull Docker images confidently; you can refer to my Docker-installation video.

https://www.bilibili.com/video/BV1RsCVYLEf6

Dockerfile

Use a multi-stage build: compile the application in a Go image during the first stage, then copy the executable to a standard container in the second stage. This greatly reduces the image size.

Docker
FROM golang:alpine AS builder

# 构建可执行文件
ENV CGO_ENABLED 0
ENV GOPROXY https://goproxy.cn,direct
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

WORKDIR /build
ADD . .
RUN go build -o main


FROM alpine
WORKDIR /app
COPY --from=builder /build/main /app
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
RUN apk add tzdata
CMD ["./main"]

After building the image, the next step is to run the container.

If the project needs MySQL, Redis, and similar services, each service would otherwise have to be run separately.

That is why Docker Compose exists.

Docker Compose defines and runs multi-container Docker applications. It uses a YAML file, usually named docker-compose.yml, to configure services, networks, volumes, and other resources, simplifying deployment and management.

Docker Compose

Configuration

YAML
version: '3.2'
services:
  mysql:
    image: "mysql:5.7"
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 123456
      TZ: Asia/Shanghai
      MYSQL_DATABASE: db
    command:
      --default-authentication-plugin=mysql_native_password
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_general_ci
      --explicit_defaults_for_timestamp=true
      --max_allowed_packet=128M;
    volumes:
      - ./mysql/data:/var/lib/mysql
      - ./mysql/blogx.sql:/docker-entrypoint-initdb.d/blogx.sql
    networks:
      blogx_network:
        ipv4_address: 10.2.0.2
  redis:
    restart: always
    image: redis:5.0.5
    networks:
      blogx_network:
        ipv4_address: 10.2.0.6
  server:
    restart: always
    image: server:v1
    networks:
      blogx_network:
        ipv4_address: 10.2.0.7
    environment:
      TZ: Asia/Shanghai
    depends_on:
      - mysql-master
      - es
      - redis
    volumes:
      - ./server/settings.yaml:/app/settings.yaml
      - ./server/uploads:/app/uploads
      - ./server/logs:/app/logs
      - ./web/dist:/app/web
    command: "/app/main"
  web:
    image: nginx:latest
    restart: always
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/logs:/var/log/nginx/
      - ./blogx_web/dist:/usr/share/nginx/fai_web
      - ./nginx/cert/:/usr/share/nginx/cert
    networks:
      blogx_network:
        ipv4_address: 10.2.0.8
    ports:
      - "80:80"
      - "443:443"
networks:  #定义容器连接网络
  blogx_network:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 10.2.0.0/24