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

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.

主站蜘蛛池模板: 宜君县| 保靖县| 仲巴县| 康平县| 都匀市| 泸州市| 玉山县| 赞皇县| 昆明市| 施秉县| 老河口市| 铜梁县| 贞丰县| 娄底市| 西充县| 大厂| 酉阳| 英超| 棋牌| 仙游县| 乌什县| 额敏县| 芜湖县| 蓝山县| 辛集市| 通州市| 安徽省| 沧州市| 绥化市| 朔州市| 海原县| 麻栗坡县| 青河县| 惠州市| 屯留县| 太白县| 顺昌县| 息烽县| 科技| 蒙自县| 龙陵县|