Skip to content

Commit d0236ac

Browse files
authored
feat: support cors (#92)
1 parent bf4bce3 commit d0236ac

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cmd/main.go

+28
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ func main() {
3333

3434
gin.SetMode(gin.ReleaseMode)
3535
r := gin.Default()
36+
37+
// if viper get cors is true, then apply corsMiddleware
38+
if viper.GetBool("cors") {
39+
log.Printf("CORS supported! \n")
40+
r.Use(corsMiddleware())
41+
}
42+
3643
registerRoute(r)
3744

3845
srv := &http.Server{
@@ -43,6 +50,26 @@ func main() {
4350
runServer(srv)
4451
}
4552

53+
// corsMiddleware sets up the CORS headers for all responses
54+
func corsMiddleware() gin.HandlerFunc {
55+
return func(c *gin.Context) {
56+
// Clear any previously set headers
57+
if c.Request.Method != "POST" {
58+
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
59+
}
60+
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
61+
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")
62+
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
63+
64+
// Handle preflight requests
65+
if c.Request.Method == "OPTIONS" {
66+
c.AbortWithStatus(200)
67+
return
68+
}
69+
c.Next()
70+
}
71+
}
72+
4673
func runServer(srv *http.Server) {
4774
go func() {
4875
log.Printf("Server listening at %s\n", srv.Addr)
@@ -66,6 +93,7 @@ func parseFlag() {
6693
pflag.StringP("configFile", "c", "config.yaml", "config file")
6794
pflag.StringP("listen", "l", ":8080", "listen address")
6895
pflag.BoolP("version", "v", false, "version information")
96+
pflag.BoolP("cors", "s", false, "cors support")
6997
pflag.Parse()
7098
if err := viper.BindPFlags(pflag.CommandLine); err != nil {
7199
panic(err)

0 commit comments

Comments
 (0)