julienschmidt/httprouter

Question: How can I embed swagger UI?

dsha256 opened this issue · 2 comments

How can I embed swagger UI? For example like so:

url := ginSwagger.URL("http://localhost:8080/swagger/doc.json")
engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
MrGlp commented

I need get all interface doc by httprouter, including, but not limited swagger, Now, is there any other ready-made solution?

Here's a vanilla solution, no server side dependencies:

Have a folder called swagger and use a static route to serve your swagger.yaml or swagger.json file and add this html file in:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="SwaggerUI" />
    <title>SwaggerUI</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css"
    />
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script
      src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-standalone-preset.js"
      crossorigin
    ></script>
    <script>
      window.onload = () => {
        var url = window.location.search.substring(1);

        if (url.length == 0) {
          url = "swagger.yaml";
        }

        window.ui = SwaggerUIBundle({
          url: url,
          dom_id: "#swagger-ui",
          deepLinking: true,
          presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
          plugins: [SwaggerUIBundle.plugins.DownloadUrl],

          layout: "StandaloneLayout",
        });
      };
    </script>
  </body>
</html>

Note: if you're using .json change the swagger.yaml to swagger.json.

Then static serve the folder from your httprouter

router.ServeFiles("/swagger/*filepath", http.Dir("swagger"))

This will serve the swagger ui file from localhost:4000/swagger/swagger.html


Aside: For generation from source code I use

Use swag or similar to annotate your route handlers

swag init -g cmd/api/main.go -o ./swagger

outputs swag files to a folder called swagger


If anyone wants an example repo, comment asking for one, and I'll make one when I have time