0Pricing
Go Academy · Lesson

CORS and Panic Recovery Middleware

Cross-origin policies and recovering from panics

CORS and Panic Recovery Middleware is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is CORS?

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts which origins can make HTTP requests to your API. The server opts in by setting response headers.

CORS preflight

Before a cross-origin request with a custom header or non-simple method, the browser sends an OPTIONS preflight. Your middleware must handle OPTIONS and return 200 with CORS headers.

CORS middleware

A simple CORS middleware for development:

func CORS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "https://myapp.com")
        w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
        w.Header().Set("Access-Control-Allow-Headers", "Authorization,Content-Type")
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusOK); return
        }
        next.ServeHTTP(w, r)
    })
}

Allowed origins

Do not use Access-Control-Allow-Origin: * when credentials (cookies, Authorization headers) are involved — use an explicit origin. Check against a whitelist for multiple origins.

allowedOrigins := map[string]bool{
    "https://app.example.com": true,
    "https://dev.example.com": true,
}

if allowedOrigins[r.Header.Get("Origin")] {
    w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
}

Access-Control-Allow-Credentials

Allow cookies and authorization headers to be sent cross-origin:

w.Header().Set("Access-Control-Allow-Credentials", "true")

rs/cors library

Use the github.com/rs/cors library for production-grade CORS with flexible origin matching, credential support, and preflight caching.

c := cors.New(cors.Options{
    AllowedOrigins: []string{"https://example.com"},
    AllowedMethods: []string{"GET","POST","PUT","DELETE"},
    AllowedHeaders: []string{"Authorization","Content-Type"},
    AllowCredentials: true,
})
handler := c.Handler(mux)

Panic recovery middleware

Recover from panics to prevent the server from crashing and losing all active connections:

func Recovery(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if rec := recover(); rec != nil {
                log.Printf("panic: %v\n%s", rec, debug.Stack())
                http.Error(w, "Internal Server Error", 500)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

runtime/debug.Stack

Print the full goroutine stack trace when a panic occurs to help diagnose the root cause:

import "runtime/debug"
log.Printf("panic: %v\n%s", rec, debug.Stack())

Sentry integration

Send panics to Sentry or similar error tracking services inside the recovery middleware before returning 500 to the client.

Order: Recovery outermost

Always register Recovery as the outermost (first-applied) middleware so it catches panics from all other middleware and handlers.

handler := Recovery(RequestID(Logger(Auth(mux))))

Testing panic recovery

Write a handler that panics deliberately, call it through the middleware in an httptest, and assert the response is 500.

panicHandler := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { panic("test") })
w := httptest.NewRecorder()
Recovery(panicHandler).ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
assert.Equal(t, 500, w.Code)

Quick Check

Why must panic recovery middleware be the outermost layer?

Recap: CORS and Panic Recovery

Key points:

  • CORS: set Access-Control-Allow-* headers; handle OPTIONS preflight
  • Allow-Origin: explicit origin (not *) when credentials involved
  • Recovery: defer recover() + log stack trace + return 500
  • Recovery must be outermost middleware

Frequently asked questions

Is the “CORS and Panic Recovery Middleware” lesson free?

Yes — the full text of “CORS and Panic Recovery Middleware” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “CORS and Panic Recovery Middleware”?

Cross-origin policies and recovering from panics You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “CORS and Panic Recovery Middleware” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. HTTP Middleware Chain Fundamentals
  2. Logging and Request ID Middleware
  3. Auth and Rate Limiting Middleware
  4. CORS and Panic Recovery Middleware
← Back to Go Academy