rss resume / curriculum vitae linkedin linkedin gitlab github twitter mastodon instagram
Go Tip: Swagger UI + CORS
Jul 26, 2018

Previously I blogged about using Dredd for verifying that the generated swagger.json is correct (from the Swagger 2.0 specification perspective, that is) now let’s take a look at another tip for making sure the final API works correctly when using Swagger UI for manual inspection.

There’s a full example showing this in action, feel free to explore the repo.


It is most likely you already enabled CORS on your web API. One way to do it, if you happen to use gorilla/mux, is to use gorilla/handlers, basically the following code:

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))

Obviously more concrete values depend on your actual needs, specially for AllowedOrigins, but for testing purposes this works.

Notice that the headers in AllowedHeaders (Authorization and Content-Type (and api_key)) are the only allowed headers to be sent by Swagger UI in your requests, without them you won’t be able to test Authentication or make request from the UI, you will either be missing those headers or you will be getting the infamous error:

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.


Back to posts