1、编写跨域处理中间件

/**
 * @Author: ldy
 * @Description: 跨域访问处理
 * @File:  CrosHandler
 * @Version: 1.0.0
 * @Date: 2020/4/28 09:39
 */
package handler

import (
	"activity/common/result"
	"github.com/gin-gonic/gin"
	"net/http"
)

//跨域访问:cross  origin resource share
func CrosHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
		context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
		context.Header("Access-Control-Max-Age", "172800")
		context.Header("Access-Control-Allow-Credentials", "false")
		context.Set("content-type", "application/json")  设置返回格式是json

		if method == "OPTIONS" {
			context.JSON(http.StatusOK, result.Result{Code: result.OK, Data: "Options Request!"})
		}

		//处理请求
		context.Next()
	}
}

2、在main.go文件中应用跨域处理中间件

func main() {
	engine := gin.Default()
	// 设置全局跨域访问
	engine.Use(handler.CrosHandler())
	// TODO 你的其他代码
	// 启动服务
	engine.Run("0.0.0.0:8080")
}

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐