当前位置:网站首页>Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
Go language web development series 28: solve cross domain access of CORS with gin contrib / CORS
2022-07-03 13:48:00 【Lao Liu, you are so awesome】
One , Libraries used for installation
1,cors The base address :
https://github.com/gin-contrib/cors
2, Install... From the command line :
[email protected]:~$ go get -u github.com/gin-contrib/cors explain : Liu Hongdi's go The forest is a focus golang The blog of ,
Address :https://blog.csdn.net/weixin_43881017
explain : author : Liu Hongdi mailbox : [email protected]
Two , Information about the demonstration project
1, Address :
https://github.com/liuhongdi/digv28
2, Functional specifications : demonstration gin The framework solves this problem by specifying the domain cors visit
3, Project structure : Pictured :

3、 ... and ,go Code instructions
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{}
}
// Return a successful prompt
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"` // Self increasing
Msg string `json:"msg"` //
Data interface{} `json:"data"`
}
func NewResult(ctx *gin.Context) *Result {
return &Result{Ctx: ctx}
}
// Return to success
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)
}
// Return failed
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()
// Handling exceptions
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))
// Path mapping :index
indexc:=controller.NewIndexController()
router.GET("/index/index", indexc.Index);
return router
}
func HandleNotFound(c *gin.Context) {
global.NewResult(c).Error(404," Resource not found ")
return
}
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// Print error stack information
log.Printf("panic: %v\n", r)
debug.PrintStack()
global.NewResult(c).Error(500," Server internal error ")
}
}()
// Finished loading defer recover, Continue with subsequent interface calls
c.Next()
}4,static/page81.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title > 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()" > visit 8080:/index/index</a><br/>
<!--====================main end=====================-->
</div>
</div>
<script>
// visit 8080:/home/home
function get_index(){
$.ajax({
type:"GET",
url:"http://127.0.0.1:8080/index/index",
// Return the format of the data
datatype: "text",//"xml", "html", "script", "json", "jsonp", "text".
processData: false,
contentType: false,
// Base note function after successful return
success:function(data){
alert(data);
if (data.code == 0){
alert(" Successful visit ");
} else {
alert(" error :"+data.msg);
}
},
// Base note
complete: function(XMLHttpRequest, textStatus){
},
// Call the function executed in error
error:function(jqXHR,textStatus,errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
</body>
</html>
Four , The test results
1, No direct access across domains :
visit :
http://127.0.0.1:8080/index/indexreturn :

2, Copy js/html To another domain
hold jquery-1.6.2.min.js and page81.html Copied to the nginx Under a virtual host , Use 80 port
3, Testing cross domain access :
http://127.0.0.1/page81.htmlreturn :

Click the link and return :

4, Test cross domain failure :
modify router/router.go in :
config.AllowOrigins = []string{"http://127.0.0.1","http://google.com", "http://facebook.com"}Get rid of the "http://127.0.0.1",
Revisit :
No response after clicking the link ,
View the console and return to :

5、 ... and , View the version of the library :
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
)
边栏推荐
- 【556. 下一个更大元素 III】
- 使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例
- 物联网毕设 --(STM32f407连接云平台检测数据)
- NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
- [556. Next larger element III]
- Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
- 刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?
- Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
- Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
- Depth and breadth first traversal of tree (regardless of binary tree)
猜你喜欢

Resolved (error in viewing data information in machine learning) attributeerror: target_ names

Students who do not understand the code can also send their own token, which is easy to learn BSC

Halcon combined with C # to detect surface defects -- Halcon routine autobahn

Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)

CVPR 2022 | 美团技术团队精选6篇优秀论文解读

SQL Injection (GET/Select)

MySQL constraints

全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场

Resource Cost Optimization Practice of R & D team

MySQL functions and related cases and exercises
随机推荐
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心
The solution of Chinese font garbled code in keil5
Realize the recognition and training of CNN images, and process the cifar10 data set and other methods through the tensorflow framework
Libuv库 - 设计概述(中文版)
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
There is nothing new under the sun. Can the meta universe go higher?
Can newly graduated European college students get an offer from a major Internet company in the United States?
[技術發展-24]:現有物聯網通信技術特點
When updating mysql, the condition is a query
SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
Logseq 评测:优点、缺点、评价、学习教程
MySQL installation, uninstallation, initial password setting and general commands of Linux
[redis] cache warm-up, cache avalanche and cache breakdown
Anan's doubts
logback日志的整理
Unity render streaming communicates with unity through JS
Windos creates Cordova prompt because running scripts is prohibited on this system
Red Hat Satellite 6:更好地管理服务器和云
MyCms 自媒体商城 v3.4.1 发布,使用手册更新