diff --git a/auth.go b/auth.go index f5f01fd..f3bc7e1 100644 --- a/auth.go +++ b/auth.go @@ -14,7 +14,6 @@ func handleAuth(c *gin.Context) error { authorization := c.Request.Header.Get("Authorization") if !strings.HasPrefix(authorization, "Bearer") { err = errors.New("authorization header should start with 'Bearer'") - c.AbortWithError(403, err) return err } @@ -24,7 +23,6 @@ func handleAuth(c *gin.Context) error { for _, auth := range strings.Split(config.Authorization, ",") { if authorization != strings.Trim(auth, " ") { err = errors.New("wrong authorization header") - c.AbortWithError(403, err) return err } } diff --git a/cors.go b/cors.go index 4603fda..e3655e6 100644 --- a/cors.go +++ b/cors.go @@ -6,14 +6,8 @@ import ( func corsMiddleware() gin.HandlerFunc { return func(c *gin.Context) { - // delete existing headers - c.Writer.Header().Del("Access-Control-Allow-Origin") - c.Writer.Header().Del("Access-Control-Allow-Methods") - c.Writer.Header().Del("Access-Control-Allow-Headers") - - // set new headers - c.Writer.Header().Set("Access-Control-Allow-Origin", "*") - c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") - c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type") + c.Header("Access-Control-Allow-Origin", "*") + c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH") + c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type") } } diff --git a/main.go b/main.go index 19f713f..fc0f92b 100644 --- a/main.go +++ b/main.go @@ -73,6 +73,9 @@ func main() { m.SetMetricPath("/v1/metrics") m.Use(engine) + // CORS middleware + engine.Use(corsMiddleware()) + // error handle middleware engine.Use(func(c *gin.Context) { c.Next() @@ -85,9 +88,6 @@ func main() { }) }) - // CORS middleware - engine.Use(corsMiddleware()) - // CORS handler engine.OPTIONS("/v1/*any", func(ctx *gin.Context) { ctx.AbortWithStatus(200) @@ -114,7 +114,10 @@ func main() { // check authorization header if !*noauth { - if handleAuth(c) != nil { + err := handleAuth(c) + if err != nil { + c.Header("Content-Type", "application/json") + c.AbortWithError(403, err) return } }