Go实战--golang中使用echo框架中的cors(labstack/echo、rs/cors)
2017-11-21 14:33
1601 查看
生命不止,继续 go go go!!!
继续搞搞echo框架,今天学习的是cors相关的内容。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
跨域资源共享( CORS )机制允许 Web 应用服务器进行跨域访问控制,从而使跨域数据传输得以安全进行。浏览器支持在 API 容器中(例如 XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 请求所带来的风险。
参考网站:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
简单请求基本流程
对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个Origin字段。
如果Origin指定的源,不在许可范围内,服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含Access-Control-Allow-Origin字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequest的onerror回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。
如果Origin指定的域名在许可范围内,服务器返回的响应,会多出几个头信息字段。
其中,
Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求。
Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。
Access-Control-Expose-Headers
该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader(‘FooBar’)可以返回FooBar字段的值。
命令行输入:
输出:
github地址:
https://github.com/rs/cors
Star: 624
文档地址:
https://godoc.org/github.com/rs/cors
代码1:
命令行输入:
输出:
代码2:
命令行输入:
输出:
继续搞搞echo框架,今天学习的是cors相关的内容。
什么是cors
CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
跨域资源共享( CORS )机制允许 Web 应用服务器进行跨域访问控制,从而使跨域数据传输得以安全进行。浏览器支持在 API 容器中(例如 XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 请求所带来的风险。
参考网站:
https://www.w3.org/TR/cors/
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
简单请求基本流程
对于简单请求,浏览器直接发出CORS请求。具体来说,就是在头信息之中,增加一个Origin字段。
如果Origin指定的源,不在许可范围内,服务器会返回一个正常的HTTP回应。浏览器发现,这个回应的头信息没有包含Access-Control-Allow-Origin字段(详见下文),就知道出错了,从而抛出一个错误,被XMLHttpRequest的onerror回调函数捕获。注意,这种错误无法通过状态码识别,因为HTTP回应的状态码有可能是200。
如果Origin指定的域名在许可范围内,服务器返回的响应,会多出几个头信息字段。
Access-Control-Allow-Origin: http://foo.com Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: FooBar Content-Type: text/html; charset=utf-8
其中,
Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求。
Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。这个值也只能设为true,如果服务器不要浏览器发送Cookie,删除该字段即可。
Access-Control-Expose-Headers
该字段可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。上面的例子指定,getResponseHeader(‘FooBar’)可以返回FooBar字段的值。
echo框架中使用cors
现在使用echo中的cors,这里官方为我们提供了源码:package main import ( "net/http" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) var ( users = []string{"Joe", "Veer", "Zion"} ) func getUsers(c echo.Context) error { return c.JSON(http.StatusOK, users) } func main() { e := echo.New() e.Use(middleware.Logger()) e.Use(middleware.Recover()) // CORS default // Allows requests from any origin wth GET, HEAD, PUT, POST or DELETE method. // e.Use(middleware.CORS()) // CORS restricted // Allows requests from any `https://labstack.com` or `https://labstack.net` origin // wth GET, PUT, POST or DELETE method. e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"http://foo.com", "http://test.com"}, AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE}, })) e.GET("/api/users", getUsers) e.Logger.Fatal(e.Start(":1323")) }
命令行输入:
curl --D - -H 'Origin: http://foo.com' http://localhost:1323/api/users
输出:
HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.com Content-Type: application/json; charset=UTF-8 Vary: Origin Date: Tue, 21 Nov 2017 06:14:23 GMT Content-Length: 21 ["Joe","Veer","Zion"]
rs/cors
Go net/http configurable handler to handle CORS requestsgithub地址:
https://github.com/rs/cors
Star: 624
文档地址:
https://godoc.org/github.com/rs/cors
代码1:
package main import ( "net/http" "github.com/rs/cors" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte("{\"hello\": \"world\"}")) }) // cors.Default() setup the middleware with default options being // all origins accepted with simple methods (GET, POST). See // documentation below for more options. handler := cors.Default().Handler(mux) http.ListenAndServe(":8080", handler) }
命令行输入:
curl -D - -H 'Origin: http://foo.com' http://localhost:8080
输出:
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Content-Type: application/json Vary: Origin Date: Tue, 21 Nov 2017 06:19:53 GMT Content-Length: 18 {"hello": "world"}
代码2:
package main import ( "net/http" "github.com/rs/cors" ) func main() { c := cors.New(cors.Options{ AllowedOrigins: []string{"http://foo.com"}, }) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte("{\"hello\": \"world\"}")) }) http.ListenAndServe(":8080", c.Handler(handler)) }
命令行输入:
curl -D - -H 'Origin: http://foo.com' http://localhost:8080
输出:
HTTP/1.1 200 OK Access-Control-Allow-Origin: http://foo.com Content-Type: application/json Vary: Origin Date: Tue, 21 Nov 2017 06:29:41 GMT Content-Length: 18 {"hello": "world"}
相关文章推荐
- Go实战--golang中使用echo框架、MongoDB、JWT搭建REST API(labstack/echo、gopkg.in/mgo.v2、dgrijalva/jwt-go)
- Go实战--golang中使用echo框架中JSONP(labstack/echo)
- Go实战--golang中使用echo框架中的HTTP/2、Server Push(labstack/echo、golang.org/x/net/http2)
- Go实战--golang中使用echo和MySQL搭建api(labstack/echo、go-sql-driver/mysql)
- Go实战--golang中使用echo嵌入静态资源(labstack/echo、GeertJohan/go.rice)
- golang实战使用gin+xorm搭建go语言web框架restgo详解4 路由配置
- golang实战使用gin+xorm搭建go语言web框架restgo详解5 控制器C
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.2 跳转和重定向
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.3 资源控制器
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.4 控制器参数绑定
- golang实战使用gin+xorm搭建go语言web框架restgo详解10 使用restgo搭建后台管理系统
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.5 控制器模型绑定
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.6 控制器参数校验
- java程序员10分钟可上手的golang框架golang实战使用gin+xorm搭建go语言web框架restgo
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.7 控制器数据响应
- golang实战使用gin+xorm搭建go语言web框架restgo详解5.9 控制器controller编程示例
- golang实战使用gin+xorm搭建go语言web框架restgo详解6.1 模型M和Orm
- golang实战使用gin+xorm搭建go语言web框架restgo详解1.1 go语言的困境
- golang实战使用gin+xorm搭建go语言web框架restgo详解6.4 推荐编程方式
- golang实战使用gin+xorm搭建go语言web框架restgo详解1.2 我要做什么