golang gin 框架启用 CORS 支持

2023-02-16  本文已影响0人  追梦人在路上不断追寻

当客户端(尤其是基于 Web 的客户端)想要访问 API 时,服务器会决定允许哪些客户端发送请求。这是通过使用称为 CORS 来完成的,它代表跨源资源共享。

image.png

跨域资源共享 (CORS) 是一种机制,允许从提供第一个资源的域之外的另一个域请求网页上的受限资源。

在gin框架中设置跨域请求非常简单,代码如下:

func CustomHeaderAPI(c *gin.Context) {
    // Add CORS headers
    c.Header("Access-Control-Allow-Origin", "http://example.com")
    c.Header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")

    // Prepare response
    c.JSON(http.StatusOK, gin.H{
        "message": "this response has custom headers"
    })
}

但是,将以下代码行添加到每个 API 中将是一种痛苦。为了使事情变得更容易,Gin 支持中间件功能。

什么是中间件功能?这是我在网上找到的一个很好的定义:

中间件函数是可以访问请求对象 ( req)、响应对象 ( res ) 以及应用程序请求-响应周期中的下一个函数的函数。

您可以自己创建中间件以启用 CORS 支持;但是,我们不想重新发明轮子!社区中的一群好人开发了一个库,以便在 Gin 中启用 CORS 支持。它被称为CORS-gin的中间件。

安装

go get github.com/gin-contrib/cors
package main

import (
 "time"

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

func main() {
 router := gin.Default()
 // CORS for https://foo.com and https://github.com origins, allowing:
 // - PUT and PATCH methods
 // - Origin header
 // - Credentials share
 // - Preflight requests cached for 12 hours
 router.Use(cors.New(cors.Config{
  AllowOrigins:     []string{"https://foo.com"},
  AllowMethods:     []string{"PUT", "PATCH"},
  AllowHeaders:     []string{"Origin"},
  ExposeHeaders:    []string{"Content-Length"},
  AllowCredentials: true,
  AllowOriginFunc: func(origin string) bool {
   return origin == "https://github.com"
  },
  MaxAge: 12 * time.Hour,
 }))
 router.Run()
}

面的配置是库为您提供的功能的最完整示例。但是,您可能不想全部使用它们。事实上,大多数项目的 CORS 配置都是相同的。为了使它更简单,包还有一个名为的东西,它返回映射到本地主机的通用默认配置。在我看来,使用此库的最佳方法是将自定义配置添加到 的结果中。例如,这是我自己的项目配置:corsDefaultConfigDefaultConfig

router := gin.Default()
corsConfig := cors.DefaultConfig()

corsConfig.AllowOrigins = []string{"https://example.com"}
// To be able to send tokens to the server.
corsConfig.AllowCredentials = true

// OPTIONS method for ReactJS
corsConfig.AddAllowMethods("OPTIONS")

// Register the middleware
router.Use(cors.New(corsConfig))
上一篇 下一篇

猜你喜欢

热点阅读