Go | gin solves cross domain problems and cross domain configuration

Time:2020-10-30

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

preface

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 (
    "github.com/gin-gonic/gin"
    "net/http"
)

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" {
            c.AbortWithStatus(http.StatusNoContent)
        }

        c.Next()
    }
}

2. Use

r := gin.Default()

r.Use(middlewares.Cors())

3. Precautions

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

Counterexample

r := gin.Default()

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

r.Use(middlewares.Cors())

This will result in cross domain configuration not taking effect

Go | gin solves cross domain problems and cross domain configuration

Recommended Today

Layout of angular material (2): layout container

Layout container Layout and container Using thelayoutDirective to specify the layout direction for its child elements: arrange horizontally(layout=”row”)Or vertically(layout=”column”)。 Note that if thelayoutInstruction has no value, thenrowIs the default layout direction. row: items arranged horizontally.max-height = 100%andmax-widthIs the width of the item in the container. column: items arranged vertically.max-width = 100%andmax-heightIs the height of the […]