Skip to content

Commit

Permalink
feat: support cors (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
fqdeng authored May 23, 2024
1 parent bf4bce3 commit d0236ac
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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)
Expand All @@ -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)
Expand Down

0 comments on commit d0236ac

Please sign in to comment.