DEV Community


Posted on

Implementing CORS with go-chi

All web browsers implement a security model known as the Same-Origin Policy (SOP). It restricts domains from accessing and retrieving data from other domains’ resources; this helps protect users from malicious scripts that could access their sensitive data or perform unauthorized actions on their behalf. This led to creation of Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

corsHandler := cors.Handler(cors.Options{
        AllowedOrigins:   []string{""},
        AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
        AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "Access-Control-Allow-Origin"},
        ExposedHeaders:   []string{"Link"},
        AllowCredentials: false,
        MaxAge:           300, // Maximum value not ignored by any of the major browsers
Enter fullscreen mode Exit fullscreen mode

The AllowedOrigins field in the corsHandler configuration in main.go specifies which origins are allowed to access the server's resources. In this case, only requests from are allowed.

This is a security measure known as Cross-Origin Resource Sharing (CORS). It prevents web pages from making requests to a different domain than the one the web page came from, unless the server specifies that it allows such requests.

If a request comes from an origin not listed in AllowedOrigins, the server will respond with a CORS error and the browser will block the request. This helps protect your server from potentially malicious requests from unknown origins.

Top comments (0)