When developing web-based APIs, especially front-end separation projects, cross-domain issues (CORS) are often encountered by front-end developers. This article will take you through what cross-domain is and how to elegantly implement a cross-domain middleware in Go, supporting your own HTTP services or frameworks such asnet/http
、Gin
wait.
What is Cross-Domain (CORS)?
CORS (Cross-Origin Resource Sharing) is a security policy for the browser that prevents web pages on one domain from making AJAX requests to another domain. For example, the front-end runs onhttp://localhost:3000
, the backend runs onhttp://localhost:8080
, this is a cross-origin request.
For security, browsers prohibit such requests by default unless the backend server explicitly declares in the response header:I allow this request to pass。
How to deal with cross-domain in Go?
In Go, we can intercept requests through middleware and add relevant CORS allow fields to the response header, so that the browser can communicate with confidence.
1. Native net/http implementation of CORS middleware
package main import ( "fmt" "net/http" ) func main() { ("/", corsMiddleware((indexHandler))) (":8080", nil) } func indexHandler(w , r *) { (w, "Hello from Go Backend") } func corsMiddleware(next ) { return (func(w , r *) { // Set CORS response header ().Set("Access-Control-Allow-Origin", "*") // All sources are allowed ().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") ().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") // If it is a pre-check request, return directly if == "OPTIONS" { () return } // Continue to process the request (w, r) }) }
Supports basic GET and POST requests and handles browserPre-flight request (OPTIONS)。
2. CORS middleware using Gin framework
If you are using the Gin framework, you can use the official recommended one/gin-contrib/cors
Plugin:
Installation dependencies:
go get /gin-contrib/cors
Sample code:
package main import ( "/gin-contrib/cors" "/gin-gonic/gin" "time" ) func main() { r := () // Use cors middleware (({ AllowOrigins: []string{"http://localhost:3000"}, // Only specific domain names are allowed AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, MaxAge: 12 * , })) ("/", func(c *) { (200, {"message": "Hello from Gin!"}) }) (":8080") }
More flexible configuration, you can set specific sources, exposed fields, whether to carry cookies, etc.
summary
Way | Features |
Nativenet/http
|
Flexible and lightweight, but requires manual setup and maintenance of response headers |
Using the Gin plugin | Convenient configuration and supports more advanced options, such as credentials, caching, etc. |
Things to note when handling cross-domain
- The development environment can be set
*
All sources are allowed, but please limit the specific domain names in the production environment to avoid security risks. - Front-end use
fetch
When , to carry cookies, you need to setcredentials: 'include'
, the backend must also be setAllowCredentials: true
。 - An OPTIONS request is a preflight request automatically sent by the browser and must return a 200 or 204 status code.
Written at the end
Implementing CORS support in a Go project is not complicated. As long as you understand the cross-domain behavior of the browser, you can easily do it through middleware. Whether you use the standard library or the Gin framework, cross-domain issues are no longer a "curse".
This is the end of this article about Go cross-domain middleware solving CORS problems. For more related Go cross-domain middleware, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!