吾八哥博客

您现在的位置是:首页 > 码农手记 > Golang > 正文

Golang

gin框架的http接口支持跨域请求的方法

吾八哥2020-04-06Golang5209

gin框架写的http接口支持跨域请求的方法很简单,实现一个支持跨域的中间件接口就行,关键代码如下:

package main

import (
	"net/http"

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

func cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		origin := c.Request.Header.Get("origin")
		if len(origin) == 0 {
			origin = c.Request.Header.Get("Origin")
		}
		c.Writer.Header().Set("Access-Control-Allow-Origin", 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", "OPTIONS, GET, POST")
		c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}

func statusOKHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

func versionHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"version": "v1.2"})
}

func main() {
	router := gin.New()
	router.Use(cors())
	router.Use(gin.Recovery())
	router.GET("/ping", statusOKHandler)
	router.GET("/version", versionHandler)
	router.Run(":8080")
}

使用go run main.go启动服务,然后使用postman来验证下:

企业微信截图_7e637270-c728-488c-9261-6fec610b1b14.png

如果要调整一些跨域的规则,则修改cors方法里的一些相关参数即可。