利用Go确保在使用Swagger UI进行手动检查时最终的API正常

100 阅读1分钟

利用Go确保在使用Swagger UI进行手动检查时最终的API正常

之前我介绍了使用Dredd来验证生成的swagger.json 是正确的(从Swagger 2.0规范的角度来看,就是这样),现在让我们来看看另一个提示,以确保在使用Swagger UI进行手动检查时,最终的API工作正常。


很可能你已经在你的网络API上启用了CORS。一种方法是,如果你碰巧使用了 gorilla/mux,就是使用 gorilla/handlers,基本上是下面的代码

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Authorization", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions})

http.ListenAndServe(":8000", handlers.CORS(originsOk, headersOk, methodsOk)(r))

显然,更多的具体数值取决于你的实际需要,特别是对于AllowedOrigins ,但对于测试来说,这个方法是可行的。

请注意,AllowedHeadersAuthorizationContent-Type (和api_key))中的头信息是Swagger UI在你的请求中唯一允许发送的头信息,没有它们,你将无法测试认证或从UI中提出请求,你要么会错过这些头信息,要么会得到臭名昭著的错误。

Failed to load http://localhost:8000/users: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.