CORS Preflight Handler

Overview

Cross-Origin Resource Sharing (CORS) specifies how a browser can access resources hosted at a location other than the original document's server. For example, JavaScript loaded from a.example.com makes a request to b.example.com.

When the request to b.example.com is not "simplearrow-up-right", the browser makes a preflight request to determine the permitted HTTP verbs, headers, origins, and some caching parameters. This behavior is an Internet WHATWG standardarrow-up-right; browsers comply with this standard to maintain secure operationarrow-up-right of webpages by preventing potential malicious behavior.

Backend Implementation

Handle OPTION request

To implement CORS preflight, the browser will send an OPTION request to the server specified in the request. Thus, the backend must handle this HTTP verb on the resource specified.

Using Gorilla, this is as easy as adding the method to the handle function

r.HandleFunc("/resource", route).Methods(http.MethodOptions)

Set Header for Allowed Origin

The allowed origin should be well-known to the server for security purposes. We'll use an environment variable.

origin := os.Getenv("ACCESS_CONTROL_ALLOW_ORIGIN")

w.Header().Set("Access-Control-Allow-Origin", origin)

Any CORS request not coming from this origin will be rejected by the browser.

Set Header for Allowed Headers

Likewise, the headers expected on this route should be well-defined in the code or configurations. We'll use a non-exported global variable here.

Set Header for Allowed Methods

Using Gorilla, this is easy as we can simply use the provided middleware function that will read the verbs configured on the handler itself.

Completed Example

You can try it out with curl, but the benefits come when we serve this resource route on b.example.com and access it via a script loaded from a.example.com -- where we're truly sharing a resource across origins.

Last updated