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")
}
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
2021-03-29 Shell中 |和||,&和&&用法
2021-03-29 shell -r参数
2018-03-29 实战:使用SVN+apache搭建一个版本控制服务器