SoFunction
Updated on 2025-03-05

Use Go to implement cross-domain resource sharing (CORS) settings

How to use Go for cross-domain resource sharing (CORS) settings?

In web development, cross-domain resource sharing (CORS) is an important security mechanism that allows many resources (such as fonts, JavaScript, etc.) to be accessed by web pages from another source on one web page. However, for security reasons, browsers prohibit such cross-domain access by default. To solve this problem, we can use Go to set up CORS.

Why do I need to set up CORS?

In web applications, we often encounter such scenarios: a web page needs to obtain resources from another source, such as loading images or JavaScript files from CDN, or obtaining data from an API service. Due to browsers' same-origin policy restrictions, these cross-domain requests are blocked by default. The CORS mechanism is designed to solve this problem, allowing the server to clearly indicate which web pages from sources can access their resources.

How to set up CORS using Go?

In Go, setting CORS usually involves setting the appropriate CORS-related header information in the HTTP response header. Here is a simple example showing how to set up CORS in Go's HTTP server:

package main

import (
 "fmt"
 "net/http"
)

func corsHandler(w , r *) {
 // Set the source that allows cross-domain access ().Set("Access-Control-Allow-Origin", "*")

 // Set the allowed request method ().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")

 // Set the allowed request header ().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

 // Preflight request cache time (seconds) ().Set("Access-Control-Max-Age", "86400")

 // Is it allowed to carry vouchers ().Set("Access-Control-Allow-Credentials", "true")

 // Handle the actual request // ...
}

func main() {
 ("/", corsHandler)
 (":8080", nil)
}

In this example, we define acorsHandlerfunction, which sets CORS-related header information in each response. We then register this function as a processor that handles the root path ("/").

  • Access-Control-Allow-Origin: Specify which source pages can access the resource. In this example, we set it to "*", which means that access from all sources is allowed. In practical applications, for security reasons, you should specify the source of access that is allowed.
  • Access-Control-Allow-Methods: Specify the allowed HTTP request methods, such as GET, POST, etc.
  • Access-Control-Allow-Headers: Specify the allowed request header.
  • Access-Control-Max-Age: Specifies the cache time (in seconds) of the preflight request. This reduces unnecessary preflight requests.
  • Access-Control-Allow-Credentials: Specify whether to allow carrying credentials (such as cookies, HTTP authentication, etc.).

Note that this is just a simple example of how to set up CORS in Go. In practical applications, you may need to make more complex configurations based on specific needs. In addition, you can also consider using third-party libraries (such as gorilla/mux, chirouter, etc.) to more conveniently manage CORS settings.

Expand knowledge: Go implements CORS (cross-domain)

Implementation principle

The cross-domain resource sharing standard describes how the new HTTP header should send requests to remote URLs in the form when the browser has permissions. Although the server will have some checksum authentication, the browser is responsible for supporting these headers and adding related restrictions. For Ajax and HTTP request methods that can modify data (especially HTTP requests other than GET, or POST requests of certain MIME type), the browser must first use the OPTIONS method to initiate a preflight request (preflight request) to know whether the server allows the cross-origin request. The actual HTTP request is initiated only after the server confirms that the permission is allowed. In the return of the preflight request, the server can also notify the client whether it is necessary to carry identity credentials (including cookies and HTTP authentication-related data).

How Go is implemented

In Golang, HTTP handlers and middleware can be used to implement CORS. Next, let's take Gin as an example

package main

import (
	"/gin-gonic/gin"
	"net/http"
)

func main() {
	router := ()

	// CORS middleware	cors := func(c *) {
		// Allow specific domains to make cross-domain requests		().Set("Access-Control-Allow-Origin", "")
		// Allow specific request methods		().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
		// Allow specific request headers		().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		// Allow identity credentials (such as cookies)		().Set("Access-Control-Allow-Credentials", "true")
		// Continue to process the request		()
	}

	// Apply CORS middleware to all routes	(cors)

	// Define a route and processor function	("/hello-world", func(c *) {
		(, "Hello, World!")
	})
	(":8080")
}

Output

[GIN-debug] GET /hello-world --> .func2 (4 handlers)
[GIN-debug] Listening and serving HTTP on :8080

In the above example, the Access-Control-Allow-Origin response header is set to specify the domain name that allows cross-domain requests. You can set it to a specific domain name, a wildcard* (allow all domain names) or dynamically get the Origin value in the request header as needed. In addition, a request method to allow, a request header, and whether to allow identity credentials (such as cookies) are also set.

test

This is verified by the command line curl. If the CORS-related header appears in the return result ( ccess-Control-Allow-Origin: * < Access-Control-Allow-Methods: * < Access-Control-Allow-Headers: * < Access-Control-Expose-Headers: * < Access-Control-Max-Age: 5 ), cross-domain success. The results are as follows:

#curl -i -k http://127.0.0.1:8080/hello-world
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Origin: 
Content-Type: text/plain; charset=utf-8
Date: Sat, 14 Oct 2023 13:42:35 GMT
Content-Length: 13

Hello, World!

This is the end of this article about using Go to implement cross-domain resource sharing (CORS) settings. For more relevant content on Go to set up CORS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!