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"
CodePudding user response:
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