From d0236acefb4c3af97f15848f547eeef276ab55d9 Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 23 May 2024 18:51:18 +0800 Subject: [PATCH] feat: support cors (#92) --- cmd/main.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/cmd/main.go b/cmd/main.go index 691b742..20e7c73 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -33,6 +33,13 @@ func main() { gin.SetMode(gin.ReleaseMode) r := gin.Default() + + // if viper get cors is true, then apply corsMiddleware + if viper.GetBool("cors") { + log.Printf("CORS supported! \n") + r.Use(corsMiddleware()) + } + registerRoute(r) srv := &http.Server{ @@ -43,6 +50,26 @@ func main() { runServer(srv) } +// corsMiddleware sets up the CORS headers for all responses +func corsMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + // Clear any previously set headers + if c.Request.Method != "POST" { + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + } + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Stainless-OS, X-STAINLESS-LANG, X-STAINLESS-PACKAGE-VERSION, X-STAINLESS-RUNTIME, X-STAINLESS-RUNTIME-VERSION, X-STAINLESS-ARCH") + c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") + + // Handle preflight requests + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(200) + return + } + c.Next() + } +} + func runServer(srv *http.Server) { go func() { log.Printf("Server listening at %s\n", srv.Addr) @@ -66,6 +93,7 @@ func parseFlag() { pflag.StringP("configFile", "c", "config.yaml", "config file") pflag.StringP("listen", "l", ":8080", "listen address") pflag.BoolP("version", "v", false, "version information") + pflag.BoolP("cors", "s", false, "cors support") pflag.Parse() if err := viper.BindPFlags(pflag.CommandLine); err != nil { panic(err)