在 golang 中启用 cors
本篇文章介绍如何在 golang 中启用和使用 cors。
go 语言 cors
跨源资源共享 (cors) 是一个基于 http 标头的过程,它定义了允许浏览器加载和使用资源的来源。 cors用于放宽同源策略策略,允许一个页面的js脚本访问其他页面的数据。
同源策略确保两个网页同源。 此策略通过隔离恶意文档来帮助提高安全性。
cors 用于通过使用表中所示的标头来放宽同源策略:
标头 | 类型 | 说明 |
---|---|---|
origin | request | 用于向服务器指示请求的来源。 |
access-control-request-method | request | 用于表示实现对服务器请求的http方法。 |
access-control-request-headers | request | 用于指示对服务器的请求中的标头。 |
access-control-allow-origin | response | 用于服务器允许的来源。 |
access-control-allow-methods | response | 用于服务器允许的以逗号分隔的方法列表。 |
access-control-allow-headers | response | 用于服务器允许的以逗号分隔的标头列表。 |
access-control-expose-headers | response | 用于允许客户端访问响应的逗号分隔标头列表。 |
access-control-max-age | response | 用于通知服务器需要多少秒来缓存对飞行前请求的响应。 |
access-control-allow-credentials | response | 用于允许或限制服务器的凭据。 |
在 golang 中启用 cors
我们可以在 go 中实现一个函数,通过使用 go 语言的 net/http 包来实现我们的 cors 策略。 按照分步过程在 go 中启用 cors
创建一个在本地主机上运行的应用程序,其端口号包含将从其他页面访问当前服务器资源的标头。 查看标题:
response_writer.header().set("content-type", "text/plain; charset=utf-8")
response_writer.header().set("access-control-allow-origin", "http://127.0.1.1:5555")
response_writer.header().set("access-control-max-age", "10")
- 如我们所见,我们启用了 cors 策略,因此来自 http://127.0.1.1:5555 的 js 脚本可以访问我们页面或资源中的数据。 最好将这些标头保存在一个方法中,以便我们可以为ag捕鱼王app官网的服务器实施 cors 策略。
-
现在为ag捕鱼王app官网的服务器设置 cors 策略; 例如,headers 的函数是 jiyikhandler。 现在这样做:
http.handlefunc("/jiyik", jiyikhandler) log.fatal(http.listenandserve(":3000", nil))
log.fatal(http.listenandserve(":3000", nil))
将为ag捕鱼王app官网的服务器设置 cors 策略。 让我们实现这个示例并查看输出。
cors 策略的 golang 文件:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.handlefunc("/jiyik", jiyikhandler)
log.println("listening the request..")
log.fatal(http.listenandserve(":3000", nil))
}
func jiyikhandler(response_writer http.responsewriter, _ *http.request) {
response_writer.header().set("content-type", "text/plain; charset=utf-8")
response_writer.header().set("access-control-allow-origin", "http://127.0.1.1:5555")
response_writer.header().set("access-control-max-age", "10")
fmt.fprintf(response_writer, "hello, this is jiyik.com!")
}
用于响应的 html/js 文件:
html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jiyiktitle>
head>
<body>
<script>
async function dorequest() {
let localhost_url = 'http://localhost:3000/jiyik';
let page_response = await fetch(localhost_url);
if (page_response.ok) {
let text = await page_response.text();
return text;
} else {
return `http error: ${page_response.status}`;
}
}
dorequest().then(data => {
document.getelementbyid("print_output").innertext = data;
});
script>
<div id="print_output">
div>
body>
html>
上面的代码会写响应你好,这里是极易网! 来自 html/js 页面中的 go 代码。
查看输出:
go 语言中的 cors 包
第三方包 cors 用于通过定义 net/http 处理程序来实现跨源资源共享。 在开始使用这个包之前,我们必须安装它。
使用以下命令:
go get github.com/rs/cors
安装成功后,我们就可以在代码中使用 cors 了。 让我们尝试一个简单的例子:
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
demo_mux := http.newservemux()
demo_mux.handlefunc("/", func(response_writer http.responsewriter, req *http.request) {
response_writer.header().set("content-type", "application/json")
response_writer.write([]byte("{\"hello!\": \"this is jiyik.com\"}"))
})
demohandler := cors.default().handler(demo_mux)
http.listenandserve(":3000", demohandler)
}
在上面的代码中,cors.default()
将设置一个具有默认选项的中间件,其中所有来源都通过 get 和 post 等简单方法接受。
查看上面代码的输出:
在 go 中将 get 和 post 方法与 cors 结合使用
我们还可以使用 get 和 post 方法通过 cors 发送请求。 我们必须使用 allowedmethods 字段在 cors 中分配它们。
让我们看例子:
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
demo_mux := http.newservemux()
demo_cors := cors.new(cors.options{
allowedorigins: []string{"*"}, //all
allowedmethods: []string{http.methodpost, http.methodget},
allowedheaders: []string{"*"}, //all
allowcredentials: false, //none
})
demo_mux.handlefunc("/jiyik", func(response_writer http.responsewriter, r *http.request) {
response_writer.header().set("content-type", "application/json")
response_writer.write([]byte("{\"hello!\": \"this is jiyik.com\"}"))
})
demo_handler := demo_cors.handler(demo_mux)
http.listenandserve(":3000", demo_handler)
}
上面的代码将使用 cors 包来实现策略并启用 get 和 post 两种方法来发送请求。
查看输出:
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
发布时间:2023/04/27 浏览次数:101 分类:
-
本篇文章介绍了在 golang 的 html 模板中使用 if-else 和 switch 循环。因此,只要输出是 html,就应该始终使用 html 模板包而不是文本模板。
发布时间:2023/04/27 浏览次数:184 分类:
-
本篇文章介绍 nil 在 golang 中的含义,nil 是 go 编程语言中的零值,是众所周知且重要的预定义标识符。
golang 中的 lambda 表达式
发布时间:2023/04/27 浏览次数:691 分类:
-
本篇文章介绍如何在 golang 中创建 lambda 表达式。lambda 表达式似乎不存在于 golang 中。 函数文字、lambda 函数或闭包是匿名函数的另一个名称。
发布时间:2023/04/27 浏览次数:136 分类:
-
当我们尝试生成对象的副本时,深层副本会准确复制原始对象的所有字段。 此外,如果它有任何对象作为字段,也会制作这些对象的副本。本篇文章介绍如何在 golang 中进行深度复制。
发布时间:2023/04/27 浏览次数:104 分类:
-
像错误一样,panic 发生在运行时。 换句话说,当您的 go 程序中出现意外情况导致执行终止时,就会发生 panics。让我们看一些例子来捕捉 golang 中的panics。
go 中的日志级别
发布时间:2023/04/27 浏览次数:585 分类:
-
本篇文章介绍如何在 golang 中创建和使用日志级别。go 中的日志级别。golang提供了一个日志包,名为log,是一个简单的日志包。 这个包不提供分级日志; 如果我们想要分级日志记录,我们必须
在 go 中使用断言
发布时间:2023/04/27 浏览次数:585 分类:
-
本篇文章介绍了 assert 在 golang 中的使用。在 go 语言中使用断言:golang 不提供对断言的任何内置支持,但我们可以使用来自 testify api 的广泛使用的第三方包断言。
go 中的随机数生成
发布时间:2023/04/27 浏览次数:206 分类:
-
本篇文章介绍如何在 go 语言中使用随机数生成功能。go 中的随机数生成 go 语言为随机数生成功能提供内置支持。 内置包 math 有方法 rand(),用于随机数生成。