当前位置:网站首页>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/index
return :
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.html
return :
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
)
边栏推荐
- JSON serialization case summary
- Go language unit test 4: go language uses gomonkey to test functions or methods
- 8皇后问题
- Swiftui development experience: the five most powerful principles that a programmer needs to master
- 编程内功之编程语言众多的原因
- 挡不住了,国产芯片再度突进,部分环节已进到4nm
- [556. Next larger element III]
- 双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
- Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
- 静态链表(数组的下标代替指针)
猜你喜欢
Screenshot of the operation steps of upload labs level 4-level 9
SQL Injection (GET/Select)
Mysql database basic operation - regular expression
用户和组命令练习
8皇后问题
【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
Kivy教程之 如何自动载入kv文件
[technology development-24]: characteristics of existing IOT communication technology
User and group command exercises
[sort] bucket sort
随机推荐
[redis] cache warm-up, cache avalanche and cache breakdown
106. How to improve the readability of SAP ui5 application routing URL
Students who do not understand the code can also send their own token, which is easy to learn BSC
Spark实战1:单节点本地模式搭建Spark运行环境
The principle of human voice transformer
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
[技术发展-24]:现有物联网通信技术特点
PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?
Bidirectional linked list (we only need to pay attention to insert and delete functions)
logback日志的整理
8 Queen question
CVPR 2022 | interpretation of 6 excellent papers selected by meituan technical team
MapReduce implements matrix multiplication - implementation code
Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
静态链表(数组的下标代替指针)
Go language unit test 3: go language uses gocovey library to do unit test
JS 将伪数组转换成数组
Task6: using transformer for emotion analysis
使用tensorflow进行完整的DNN深度神经网络CNN训练完成图片识别案例