- 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.
- DevOps:軟件架構師行動指南
- Android項目開發入門教程
- 數據結構和算法基礎(Java語言實現)
- Java技術手冊(原書第7版)
- 精通軟件性能測試與LoadRunner實戰(第2版)
- 網站構建技術
- C語言程序設計
- Learning Unreal Engine Android Game Development
- C#程序設計(項目教學版)
- Nagios Core Administration Cookbook(Second Edition)
- 硬件產品設計與開發:從原型到交付
- Node.js從入門到精通
- Application Development with Parse using iOS SDK
- Python數據預處理技術與實踐
- Java Web動態網站開發(第2版·微課版)