官术网_书友最值得收藏!

CORS

Assuming your users are using a desktop browser that has been released in the last five years, or a mobile browser such as iOS 9 or Android 4.2+, then implementing CORS will be more than enough. http://caniuse.com/#feat=cors says that it is over 92% of all Internet users. I was looking forward to bashing IE for the lack of full adoption; however, since this has been supported since IE8 I will have to complain about mobile users.

CORS is a W3C proposal to standardize cross-origin requests from the browser. It works by the browsers built in HTTP client making an OPTIONS request to a URI before the real request.

If the server at the other end returns a header that contains the origin of the domain from which the script is being loaded, then the browser will trust the server and will allow a cross-site request to be made:

Access-Control-Allow-Origin: origin.com 

Implementing this in Go is quite straightforward and we could create a middleware to globally manage this for us. For simplicity, in our example we have hard coded this into the handler:

Example 2.2 chapter2/cors/cors.go

25 if r.Method == "OPTIONS" { 
26 w.Header().Add("Access-Control-Allow-Origin", "*")
27 w.Header().Add("Access-Control-Allow-Methods", "GET")
28 w.WriteHeader(http.StatusNoContent)
29 return
30 }

In line 25, we detect if the request method is OPTIONS and instead of returning the response we return the Access-Control-Allow-Origin header that the client is expecting. In our example, we are simply returning \*, which means all domains are allowed to interact with this API. This is not the safest implementation and quite often you will request your API users to register the domains that will be interacting with the API and restrict the Allow-Origin to only include those domains. In addition to the Allow-Origin header we are also returning the following:

Access-Control-Allow-Methods: GET 

This tells the browser that it can only make GET requests to this URI and that it is forbidden to make POST, PUT, and so on. This is an optional header, but it can be used to enhance your user's security when interacting with the API. One thing to note is that we are not sending back a 200 OK response we are using 204 No Content since it is invalid to return a body with an OPTIONS request.

主站蜘蛛池模板: 邵武市| 清远市| 永宁县| 武宁县| 巨野县| 安化县| 潮安县| 珠海市| 东方市| 叶城县| 海南省| 东台市| 威海市| 肥乡县| 玉溪市| 梁平县| 广丰县| 江孜县| 天台县| 泾阳县| 南郑县| 翁牛特旗| 富平县| 阳谷县| 会泽县| 东明县| 微山县| 昌邑市| 鄄城县| 梓潼县| 淮滨县| 龙口市| 雅江县| 龙州县| 石嘴山市| 休宁县| 贡觉县| 浑源县| 吴忠市| 古交市| 平山县|