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. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.
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
Learn Go with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “CORS and Panic Recovery Middleware” lesson free?
Yes — any 3 lessons of the Go Academy learning path, including “CORS and Panic Recovery Middleware”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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
- HTTP Middleware Chain Fundamentals
- Logging and Request ID Middleware
- Auth and Rate Limiting Middleware
- CORS and Panic Recovery Middleware