In this article, we will see how to resolve the cross-origin request blocked error in golang.

When a browser encounters a request from a different origin, it sends an HTTP OPTIONS request to the server before making the actual request. The server responds with CORS headers that allow or restrict access to the requested resource.

If the server does not include the necessary CORS headers or includes restrictive headers, then the browser blocks the request and displays a “Cross-Origin Request Blocked” error.

Following are some of the common reasons for this error:

  1. Incorrect CORS headers – Appropriate CORS headers should be included in the server’s response to indicate which origins are allowed to access the resources. Specifying incorrect values or not indicating these headers can result in CORS errors.
  2. Invalid Origin whitelisting – If the server’s CORS configuration has only specific origins listed using the Access-Control-Allow-Origin header, then the requests from unauthorized or unlisted origins will be blocked.

Handle CORS error in golang

The CORS issues in Go can be addressed by implementing the custom middleware to handle CORS-related headers. The middleware can be registered on specific routes or globally and should set the necessary CORS header in the response.

Following is an example using the Gorilla Mux library:

package main

import (
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()

	// CORS middleware
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Set CORS headers
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

			// Continue with the request
			next.ServeHTTP(w, r)
		})
	})

	// Add your routes

	http.ListenAndServe(":8080", r)
}

In the above example, the middleware sets permissive CORS headers that allow requests from any origin (*). We can also adjust the Access-Control-Allow-Origin value & list the needed origins to restrict access to specific origins.

Categorized in:

Tagged in: