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 "simple", the browser makes a preflight request to determine the permitted HTTP verbs, headers, origins, and some caching parameters. This behavior is an Internet WHATWG standard; browsers comply with this standard to maintain secure operation 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
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.