go的gin跨域中间件
func
CORSMiddleware() gin.HandlerFunc {
return
func
(c *gin.Context) {
c.Writer.Header().Set(
"Access-Control-Allow-Origin"
,
"*"
)
c.Writer.Header().Set(
"Access-Control-Allow-Credentials"
,
"true"
)
c.Writer.Header().Set(
"Access-Control-Allow-Headers"
,
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With"
)
c.Writer.Header().Set(
"Access-Control-Allow-Methods"
,
"POST, OPTIONS, GET, PUT"
)
if
c.Request.Method ==
"OPTIONS"
{
c.AbortWithStatus(204)
return
}
c.Next()
}
}
package handler
import (
"github.com/gin-gonic/gin"
"net/http"
"sshfortress/model"
"strings"
)
const jwtCtxUidKey = "authedUserId"
const bearerLength = len("Bearer ")
func JwtMiddleware(c *gin.Context) {
token, ok := c.GetQuery("_t")
if !ok {
hToken := c.GetHeader("Authorization")
if len(hToken) < bearerLength {
c.AbortWithStatusJSON(http.StatusPreconditionFailed, gin.H{"msg": "header Authorization has not Bearer token"})
return
}
token = strings.TrimSpace(hToken[bearerLength:])
}
userId, err := model.JwtParseUser(token)
if err != nil {
c.AbortWithStatusJSON(http.StatusPreconditionFailed, gin.H{"msg": err.Error()})
return
}
//store the user Model in the context
c.Set(jwtCtxUidKey, userId)
c.Next()
// after request
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow- Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}
3)在所有接口前增加router.Use(Cors()),放行所有的借口请求;
func Login_api_start() {
router := gin.Default()
//放行所有的请求
router.Use(Cors())
//用户登录接口
router.POST("/userlogin", Userlogin)
//新增支出接口
router.GET("/sub",Subtraction)
//新增收入接口
router.GET("/add",Add)
//获取到字典表
router.GET("/getdict",Getdict)
//获取到支出信息
router.GET("/getsub",Getsubtraction)
//获取到每个人支出和收入的占比
router.GET("/statistics",Statistics)
router.Run(":8081")
}