您的位置:首页 > 编程语言 > Go语言

Go实战--golang中使用echo框架中的cors(labstack/echo、rs/cors)

2017-11-21 14:33 1601 查看
生命不止,继续 go go go!!!

继续搞搞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 requests

github地址:

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"}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐