- Building Microservices with Go
- Nic Jackson
- 378字
- 2021-07-15 17:28:13
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.
- 軟件項目估算
- The Supervised Learning Workshop
- TypeScript入門與實戰(zhàn)
- PowerCLI Cookbook
- 深入實踐Spring Boot
- oreilly精品圖書:軟件開發(fā)者路線圖叢書(共8冊)
- DevOps Automation Cookbook
- R語言與網絡輿情處理
- Python機器學習:預測分析核心算法
- Android開發(fā)三劍客:UML、模式與測試
- JavaScript+jQuery網頁特效設計任務驅動教程
- R Data Science Essentials
- Learning iOS Security
- SEO教程:搜索引擎優(yōu)化入門與進階(第3版)
- Visual C++程序設計與項目實踐