Kofi A. Asare

Aspiring Software Engineer

github email
Responding To Cors Preflight Request in Go
Oct 18, 2018
One minute read

Using the iris web framework, I created a middleware to respond to all cors preflight requests.

  
    func corsMiddleware(ctx iris.Context) {
        var (
            corsOrigin             = ctx.GetHeader("Origin")
            corsMethod             = ctx.GetHeader("Access-Control-Request-Method")
            corsHeaders            = ctx.GetHeader("Access-Control-Request-Headers")
            isCorsPreflightRequest = (corsOrigin != "") || (corsMethod != "") || (corsHeaders != "")
        )

        if isCorsPreflightRequest {
            ctx.Header("Access-Control-Allow-Origin", corsOrigin)
            ctx.Header("Access-Control-Allow-Methods", corsMethod)
            ctx.Header("Access-Control-Allow-Headers", corsHeaders)
            ctx.Header("Access-Control-Max-Age", string(60*60*24))
            if ctx.Request().Method == "OPTIONS" {
                ctx.StatusCode(200)
                return
            }
        }

        ctx.Next()
    }

    func main() {
        app := iris.New()
        app.UseGlobal(corsMiddleware)
    }

    

Tags: http cors go iris

All Posts