CORS
CORS is a browser rule: a page on one origin may read a response from another only if the server lists that origin in Access-Control-Allow-Origin. In Go you set those headers in middleware, including on the OPTIONS preflight.
Detailed Explanation
A SPA on https://app.example.com calls https://api.example.com. The browser sends Origin and, for "non-simple" requests, an OPTIONS preflight with Access-Control-Request-Method and Access-Control-Request-Headers. Your API must reply with allowing headers or the browser hides the response from JavaScript.
The headers. Access-Control-Allow-Origin is either a specific origin or, with care, *. * cannot be used with Allow-Credentials: true. Allow-Methods and Allow-Headers answer the preflight. Allow-Credentials is needed for cookies. Max-Age caches the preflight.
Middleware. Check r.Method == http.MethodOptions and write 204 with the CORS headers, without running the real handler. For other methods, set the headers then call next. Reflecting any Origin is an open API to every website; allow-list the origins you own.
net/http has no CORS helper in the standard library. A twenty-line middleware is enough. Third-party packages exist; they still set the same headers.
What it costs. A wrong * plus cookies is a credential leak to any origin. A missing preflight handler looks like a network error in the browser and a 405 in server logs. Test with Origin set, not only with curl (curl does not enforce CORS).
Code Examples
package main
import "net/http"
func CORS(next http.Handler, origin string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
mux := http.NewServeMux()
http.ListenAndServe(":8080", CORS(mux, "https://app.example.com"))
}Common Gotchas
`curl` success does not prove CORS
use a browser or an `Origin` header and inspect `Access-Control-*`.
Preflight is `OPTIONS`
the mux must not 405 that method for API routes.