Go | gin solves cross domain problems and cross domain configuration


<h1>Go | gin solves cross domain problems and cross domain configuration</h1>


In the project of separating front end and back end, we often encounter cross domain problems. How to solve the problems?!

1、 About cross domain solutions

Most of the cross domain solutions can be divided into two types

  1. Nginx reverse proxy solves cross domain problem
  2. The server sets theAccess-Control-Allow-Origin

For the back-end development, the second kind of operational update is flexible. Here’s how gin achieves it

2、 How to use it

In gin, middleware is provided to process the response logic before and after a request. Here, we use the middle to add each requestAccess-Control-Allow-Originhead

1. Write a middleware

suremiddlewaresCreate under package

package middlewares

import (

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method
        if origin != "" {
        //You can replace * with the specified domain name
            c.Header("Access-Control-Allow-Origin", "*") 
            c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
            c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
            c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
            c.Header("Access-Control-Allow-Credentials", "true")

        if method == "OPTIONS" {


2. Use

r := gin.Default()


3. Precautions

Need tor.Use(middlewares.Cors())Set before using routing, otherwise it will not take effect


r := gin.Default()

pingGroup := r.Group("ping")
    pingGroup.GET("/", Ping)


This will result in cross domain configuration not taking effect

Go | gin solves cross domain problems and cross domain configuration