Before we cover CORS handling in javascript and Golang, let’s first have a bird’s view of the CORS and why we need to enable it in our code.[1] # **A Bird’s Eye View of the CORS** Let’s say your server runs on https://www.domain1.com. You could load images and fonts or have other web services that send back some data. Let’s imagine another website that runs on https://www.domain2.com that wants to access your services and get some data from your server. This website sends HTTP request to one of your API endpoints to get this job done.[2] Every HTTP request comes with request headers that contain information about the request. So, in our example, when https://www.domain2.com sends an HTTP request to your server that contains the origin property. This origin property specifies the domain of the source that made the request. The browser on which domain 2 sends a request has a built-in security feature same-origin policy. Because of this policy, the browser blocks all requests from different origins. Therefore, by default, browsers strictly prohibit cross-origin resource sharing. [3] This built-in security feature of the web browser prevents your data from being stolen. # **Enabling CORS in Javascript** In Javascript, we typically allow CORS on the server side; however, on the client side, we can specify additional headers to inform the server that the Javascript code will access the resources from different origins. ``` // Make a cross-origin request using XMLHttpRequest or fetch API const url = 'https://example.com/api/data'; const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); // Include CORS headers xhr.setRequestHeader('Content-Type', 'application/json'); xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); // Replace * with your domain if needed xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // Specify allowed HTTP methods xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept'); // Specify allowed headers xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // Handle the response const response = JSON.parse(xhr.responseText); console.log(response); } }; xhr.send(); ``` # Enabling CORS in the Golang In Golang, you can allow CORS by adding middleware to your server that sets the necessary headers. Here is the code to show you how to allow CORS with Golang using the Gorilla mux router(): ``` package main import ( "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() // Enable CORS middleware router.Use(enableCORS) // Define your API routes router.HandleFunc("/api/data", handleAPIRequest) // Start the server http.ListenAndServe(":8000", router) } // Middleware to enable CORS func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow requests from any origin w.Header().Set("Access-Control-Allow-Origin", "*") // Allow specified HTTP methods w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") // Allow specified headers w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept") // Continue with the next handler next.ServeHTTP(w, r) }) } // Handler for your API request func handleAPIRequest(w http.ResponseWriter, r *http.Request) { // Handle the API request // ... } ``` In summary, to allow CORE * In Javascript, we use the setRequestHeader() method to include CORS headers necessary to enable cross-origin resource sharing. Its various headers required for CORS include: ‘Content-Type,’ ‘Access-Control-Allow-Origin,’ ‘Access Control-Allow-Methods,’ and ‘Access-Control-Allow-Headers.’ * In Golang, we use the `enableCORS` function as a middleware that sets the necessary headers for Cross-Origin Resource Sharing. The `enableCORS` function is called in the router setup using the `router. Use(enableCORS)` to apply it as middleware to all the routes. Since it is a middleware, it modifies the response headers to allow cross-origin requests. # References [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS [2] https://www.ibm.com/docs/en/cics-ts/5.3?topic=protocol-http-requests#:~:text=An%20HTTP%20request%20is%20made,needed%20to%20access%20the%20resource. [3] https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy