英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论