From 577bf91d25aaa9151c33891ac9989d9e51a3de64 Mon Sep 17 00:00:00 2001 From: Yang Luo Date: Tue, 26 Sep 2023 00:02:31 +0800 Subject: [PATCH] Refactor out setCorsHeaders() --- routers/cors_filter.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/routers/cors_filter.go b/routers/cors_filter.go index 61337153..1bc81826 100644 --- a/routers/cors_filter.go +++ b/routers/cors_filter.go @@ -29,21 +29,23 @@ const ( headerAllowHeaders = "Access-Control-Allow-Headers" ) +func setCorsHeaders(ctx *context.Context, origin string) { + ctx.Output.Header(headerAllowOrigin, origin) + ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS, DELETE") + ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization") +} + func CorsFilter(ctx *context.Context) { origin := ctx.Input.Header(headerOrigin) originConf := conf.GetConfigString("origin") if ctx.Request.Method == "POST" && ctx.Request.RequestURI == "/api/login/oauth/access_token" { - ctx.Output.Header(headerAllowOrigin, origin) - ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS, DELETE") - ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization") + setCorsHeaders(ctx, origin) return } if ctx.Request.RequestURI == "/api/userinfo" { - ctx.Output.Header(headerAllowOrigin, origin) - ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS, DELETE") - ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization") + setCorsHeaders(ctx, origin) return } @@ -54,9 +56,7 @@ func CorsFilter(ctx *context.Context) { } if ok { - ctx.Output.Header(headerAllowOrigin, origin) - ctx.Output.Header(headerAllowMethods, "POST, GET, OPTIONS, DELETE") - ctx.Output.Header(headerAllowHeaders, "Content-Type, Authorization") + setCorsHeaders(ctx, origin) } else { ctx.ResponseWriter.WriteHeader(http.StatusForbidden) return