Gin 全局 Basic Auth

網上一堆都是莫名其妙的寫法

package main

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

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		username, password, status := c.Request.BasicAuth()
		errMsg := "The authentication is failed"
		if !status {
			c.AbortWithStatusJSON(401, gin.H{"error": errMsg})
			return
		}
		if !validateUser(username, password) {
			c.AbortWithStatusJSON(401, gin.H{"error": errMsg})
			return
		}
		c.Next()
	}
}

func validateUser(username string, password string) bool {
	// 認證處理邏輯
	log.Printf(username)
	log.Println(password)
	return true
}

func main() {
	api = gin.Default()
	api.Use(AuthMiddleware(ac))
	_ = api.Run(":8080")
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章