有没有办法在Gin Go中为单个路由启用CORS?

huangapple go评论117阅读模式
英文:

Is there a way to make CORS work for a single route in Gin Go

问题

我正在尝试让一个单独的gin服务器端点只能被特定的来源访问。我尝试了一些包,比如https://github.com/gin-contrib/cors,但据我了解,它会将CORS设置为整个服务器。

例如,我有多个路由,但我只想让"/scrape"这个路由可以被"google.com"访问。

  • /data "所有来源"
  • /ping "所有来源"
  • /scrape "google.com"
英文:

I am trying to make a single gin server endpoint be accessible by a certain origin. I have tried some packages such as https://github.com/gin-contrib/cors but from what I understand it sets CORS to your whole server.

For example I have multiple routes but I only want "/scrape" to be allowed to be accessed by "google.com"

  • /data "all origins"
  • /ping "all origins"
  • /scrape "google.com"

答案1

得分: 1

当然可以。它(https://github.com/gin-contrib/cors)只是一个中间件

package main

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

func main() {
  router := gin.Default()

  // CORS for example.com and example.net origins
  router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"example.com"},
    AllowOriginFunc: func(origin string) bool {
      return origin == "example.net"
    }})).GET("/scrape", func(c *gin.Context) {
     // serve something
  })

  allOrigins := router.Group("/")
  allOrigins.Use(cors.Default())
  allOrigins.GET("/data", func(c *gin.Context) {
     // serve something
  })
  allOrigins.GET("/ping", func(c *gin.Context) {
     // serve something
  })

  router.Run()
}

查看更多中间件示例:https://github.com/gin-gonic/gin#using-middleware

英文:

Of course you can. It(https://github.com/gin-contrib/cors) just a middleware.

package main

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

func main() {
  router := gin.Default()

  // CORS for example.com and example.net origins
  router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"example.com"},
    AllowOriginFunc: func(origin string) bool {
      return origin == "example.net"
    }})).GET("/scrape", func(c *gin.Context) {
     // serve something
  })

  allOrigins := router.Group("/")
  allOrigins.Use(cors.Default())
  allOrigins.GET("/data", func(c *gin.Context) {
     // serve something
  })
  allOrigins.GET("/ping", func(c *gin.Context) {
     // serve something
  })

  router.Run()
}

See more middleware example: https://github.com/gin-gonic/gin#using-middleware

huangapple
  • 本文由 发表于 2022年9月5日 08:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/73603653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定