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

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

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)只是一个中间件

  1. package main
  2. import (
  3. "github.com/gin-contrib/cors"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. router := gin.Default()
  8. // CORS for example.com and example.net origins
  9. router.Use(cors.New(cors.Config{
  10. AllowOrigins: []string{"example.com"},
  11. AllowOriginFunc: func(origin string) bool {
  12. return origin == "example.net"
  13. }})).GET("/scrape", func(c *gin.Context) {
  14. // serve something
  15. })
  16. allOrigins := router.Group("/")
  17. allOrigins.Use(cors.Default())
  18. allOrigins.GET("/data", func(c *gin.Context) {
  19. // serve something
  20. })
  21. allOrigins.GET("/ping", func(c *gin.Context) {
  22. // serve something
  23. })
  24. router.Run()
  25. }

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

英文:

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

  1. package main
  2. import (
  3. "github.com/gin-contrib/cors"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. router := gin.Default()
  8. // CORS for example.com and example.net origins
  9. router.Use(cors.New(cors.Config{
  10. AllowOrigins: []string{"example.com"},
  11. AllowOriginFunc: func(origin string) bool {
  12. return origin == "example.net"
  13. }})).GET("/scrape", func(c *gin.Context) {
  14. // serve something
  15. })
  16. allOrigins := router.Group("/")
  17. allOrigins.Use(cors.Default())
  18. allOrigins.GET("/data", func(c *gin.Context) {
  19. // serve something
  20. })
  21. allOrigins.GET("/ping", func(c *gin.Context) {
  22. // serve something
  23. })
  24. router.Run()
  25. }

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:

确定