go语言web开发系列之二十八:用gin-contrib/cors解决cors跨域访问

一,安装用到的库

1,cors库地址:

GitHub - gin-contrib/cors: Official CORS gin's middleware

2,从命令行安装:

liuhongdi@ku:~$ go get -u github.com/gin-contrib/cors

说明:刘宏缔的go森林是一个专注golang的博客,
网站:https://blog.imgtouch.com
原文: go语言web开发系列之二十八:用gin-contrib/cors解决cors跨域访问 – 架构森林

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,地址:

GitHub - liuhongdi/digv28: 用gin-contrib/cors解决cors跨域访问

2,功能说明:演示gin框架通过指定域来解决cors访问

3,项目结构:如图:

三,go代码说明

1,controller/indexController.go

package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/liuhongdi/digv28/global"
	"time"
)

type IndexController struct{}
func NewIndexController() IndexController {
	return IndexController{}
}
//返回一个成功的提示
func (g *IndexController) Index(c *gin.Context) {
	fmt.Println("controller:index: "+time.Now().String())
	result := global.NewResult(c)
	result.Success("success");
	return
}

2,global/result.go

package global

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Result struct {
	Ctx *gin.Context
}

type ResultCont struct {
	Code	int  `json:"code"` // 自增
	Msg string  `json:"msg"` //
	Data interface{} `json:"data"`
}

func NewResult(ctx *gin.Context) *Result {
	return &Result{Ctx: ctx}
}

//返回成功
func (r *Result) Success(data interface{}) {
	if (data == nil) {
		data = gin.H{}
	}
	res := ResultCont{}
	res.Code = 0
	res.Msg = ""
	res.Data = data
	r.Ctx.JSON(http.StatusOK,res)
}

//返回失败
func (r *Result)Error(code int,msg string) {
	res := ResultCont{}
	res.Code = code
	res.Msg = msg
	res.Data = gin.H{}
	r.Ctx.JSON(http.StatusOK,res)
	r.Ctx.Abort()
}

3,router/router.go

package router

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/liuhongdi/digv28/controller"
	"github.com/liuhongdi/digv28/global"
	"log"
	"runtime/debug"
)

func Router() *gin.Engine {
	router := gin.Default()
	//处理异常
	router.NoRoute(HandleNotFound)
	router.NoMethod(HandleNotFound)
	router.Use(Recover)
	//cors
	config := cors.DefaultConfig()
	//config.AllowOrigins = []string{"http://127.0.0.1","http://google.com", "http://facebook.com"}
	config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
	router.Use(cors.New(config))

	// 路径映射:index
	indexc:=controller.NewIndexController()
	router.GET("/index/index", indexc.Index);

	return router
}

func HandleNotFound(c *gin.Context) {
	global.NewResult(c).Error(404,"资源未找到")
	return
}

func Recover(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			//打印错误堆栈信息
			log.Printf("panic: %v\n", r)
			debug.PrintStack()
			global.NewResult(c).Error(500,"服务器内部错误")
		}
	}()
	//加载完 defer recover,继续后续接口调用
	c.Next()
}

4,static/page81.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title >标题</title>
    <meta charset="utf-8" />
    <script type="text/javascript" language="JavaScript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
<div id="content" style="width:800px;">
    <div style="width:250px;float:left;font-size: 16px;" ></div>
    <div style="width:550px;float:left;">
        <!--====================main begin=====================-->
        <a href="javascript:get_index()" >访问8080:/index/index</a><br/>
        <!--====================main   end=====================-->
    </div>
</div>
<script>
    //访问8080:/home/home
    function get_index(){
        $.ajax({
            type:"GET",
            url:"http://127.0.0.1:8080/index/index",
            //返回数据的格式
            datatype: "text",//"xml", "html", "script", "json", "jsonp", "text".
            processData: false,
            contentType: false,
            //成功返回之后调用的函数
            success:function(data){
                alert(data);
                if (data.code == 0){
                    alert("访问成功");
                } else {
                    alert("出错:"+data.msg);
                }
            },
            //调用执行后调用的函数
            complete: function(XMLHttpRequest, textStatus){
            },
            //调用出错执行的函数
            error:function(jqXHR,textStatus,errorThrown){
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    }
</script>
</body>
</html>

四,测试效果

1,不跨域直接访问:

   访问:

http://127.0.0.1:8080/index/index

返回:

2,  复制js/html到另外一个域

     把jquery-1.6.2.min.js和page81.html复制到nginx的一个虚拟主机下,使用80端口

3,测试跨域访问:

http://127.0.0.1/page81.html

返回:

点击链接后返回:

4,测试跨域失败:

  修改router/router.go中:

config.AllowOrigins = []string{"http://127.0.0.1","http://google.com", "http://facebook.com"}

去掉其中的 "http://127.0.0.1",

再次访问:

点击链接后无响应,
查看控制台返回:

五,查看库的版本:

module github.com/liuhongdi/digv28

go 1.15

require (
	github.com/gin-gonic/gin v1.6.3
	github.com/gin-contrib/cors v1.3.1
)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老刘你真牛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值