Go CORS Middleware
Implement CORS middleware in Go with configurable allowed origins, methods, headers, preflight request handling, and credential support for cross-origin API.
Code
package main
import (
"net/http"
"strings"
)
func corsMiddleware(allowedOrigins []string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
for _, allowed := range allowedOrigins {
if origin == allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
break
}
}
if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK); return }
next.ServeHTTP(w, r)
})
}How it works
All of the logic lives in the function corsMiddleware.
Repetition is confined to for _, allowed := range allowedOrigins — the rest of the file is straight-line.
What to watch for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Putting it to use
The operative signature is func corsMiddleware(allowedOrigins []string, next http.Handler) http.Handler
The core lines, annotated
if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK); return }
for _, allowed := range allowedOrigins {
if origin == allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
break
}
}
Interactive Tools for This Topic
CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `net/http`, `strings`. The file defines `corsMiddleware` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.