SoFunction
Updated on 2025-03-05

Detailed explanation of how to implement CORS (cross-domain) in Golang

What is cross-domain

If the protocol, port (if specified) and host of both URLs are the same, the two URLs are the same. For example

URL result reason
/dir2/ Homogenous Only the path is different
/dir/inner/ Homogenous Only the path is different
/ fail Different agreements
:81/dir/ fail Different ports (http:// The default port is 80)
:81/dir/ fail Different hosts

What is CORS

Cross-origin resource sharing (CORS), a mechanism used to enable restricted resources of web pages to be accessed by pages of other domain names. Through this mechanism, the page can freely use pictures, styles, scripts, iframes and videos from different sources. Some cross-domain requests (especially Ajax) are often prohibited by Same-origin policy. Cross-origin resource sharing defines a way to enable browsers and servers to confirm that they are secure enough to use cross-origin requests. This will be more free and functional than pure homologous requests, but safer than pure cross-origin requests. ---Wikipedia

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!

Success

The above is a detailed explanation of how to implement CORS (cross-domain) in Golang. For more information about Golang's implementation of CORS, please pay attention to my other related articles!