SoFunction
Updated on 2025-03-05

Golang gin cross-domain solution example

gin cross-domain solution

package middlewares
import (
	"/gin-gonic/gin"
	"net/http"
)
func Cors()  {
	return func(c *) {
		method := 
		origin := ("Origin")
		if origin != ""{
			("Access-Control-Allow-Origin", origin)
			//Mainly set Access-Control-Allow-Origin			("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			("Access-Control-Allow-Credentials", "false")
			("content-type", "application/json")
		}
		if method == "OPTIONS"{
			()
		}
		()
	}
}

func Cors()  {
	return ({
		AllowAllOrigins: false,
		AllowOrigins:    nil,
		AllowOriginFunc: func(origin string) bool {
			return true
		},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
		AllowHeaders:     []string{"Authorization", "ts", "Accept", "Origin", "DNT", "X-CustomHeader", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Content-Range", "Range"},
		AllowCredentials: true,
		MaxAge:           10 * ,
	})
}

Using middleware

package router
import (
    "/gin-gonic/gin"
    "goproejct/controllers"
    "goproejct/middlewares"//Introduce middleware goproject as project name according to your own situation)
func InitRouter() {
    router := ()
    (Cors())//Use middleware    v1 := ("v1")
    {
        ("/login", )
        ("/regist", )
    }
    (":8000")
}

The above is the detailed content of Golang gin cross-domain solution. For more information about gin-cross-domain solution, please follow my other related articles!