SoFunction
Updated on 2025-04-07

Implementation of cross-domain resource sharing for multiple domain names in Golang

In Golang, cross-domain resource sharing (CORS) of multiple domain names can be handled through dynamic inspectionOriginAnd set the response header to achieve it. The following is an implementation example based on Golang.

1. Dynamically judge the domain name and set CORS

According to the requestOrigin, determine whether it is allowed, and dynamically setAccess-Control-Allow-Origin

Sample code

package main

import (
	"net/http"
)

func main() {
	allowedOrigins := []string{
		"",
		"",
		"",
	}

	("/", func(w , r *) {
		origin := ("Origin")
		for _, o := range allowedOrigins {
			if origin == o {
				().Set("Access-Control-Allow-Origin", origin)
				().Set("Access-Control-Allow-Credentials", "true")
				().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
				().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
				break
			}
		}

		// Handle preflight request
		if  ==  {
			()
			return
		}

		// Example response for other requests
		([]byte("CORS configured!"))
	})

	(":8080", nil)
}

2. Use third-party libraries (Gin framework)

If you use Gin, you can implement CORS for dynamic domain names through middleware.

Sample code

package main

import (
	"/gin-gonic/gin"
)

func main() {
	allowedOrigins := []string{
		"",
		"",
		"",
	}

	r := ()

	// Custom middleware processing CORS	(func(c *) {
		origin := ("Origin")
		for _, o := range allowedOrigins {
			if origin == o {
				().Set("Access-Control-Allow-Origin", origin)
				().Set("Access-Control-Allow-Credentials", "true")
				().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
				().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
				break
			}
		}

		// If it is an OPTIONS request, return in advance		if  == "OPTIONS" {
			(204)
			return
		}

		()
	})

	("/", func(c *) {
		(200, {"message": "CORS configured!"})
	})

	(":8080")
}

3. Nginx cooperates with Golang to implement multiple domain names CORS

If Nginx is used as the reverse proxy, CORS's domain name filtering can be handled at the Nginx layer. The specific configuration is as follows:

Example Nginx configuration

server {
    listen 80;
    server_name ;

    location / {
        set $cors "";
        if ($http_origin ~* "(https://example1\.com|https://example2\.com|https://example3\.com)") {
            set $cors $http_origin;
        }
        add_header Access-Control-Allow-Origin $cors;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type, Authorization";

        # Pass the request to your Golang app
        proxy_pass http://127.0.0.1:8080;
    }
}

Things to note

  • OPTIONS request processing:

    • An OPTIONS request is a preflight request sent by the browser to check whether cross-domain is allowed.
    • A quick response to the OPTIONS request must be returned with a 204 status code.
  • Security:

    • Make sure only trustworthy ones are allowedOrigin
    • Prevent CORS header injection vulnerabilities and strictly verify the request header.
  • Access-Control-Allow-Credentialslimit:

    • If setAccess-Control-Allow-Credentials: trueAccess-Control-Allow-OriginCan't be*, the specific domain name must be specified.

This is the article about the implementation of cross-domain resource sharing of multiple domain names in Golang. For more related content on cross-domain resource sharing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!