julienschmidt / httprouter

A high performance HTTP request router that scales well
https://pkg.go.dev/github.com/julienschmidt/httprouter
BSD 3-Clause "New" or "Revised" License
16.59k stars 1.47k forks source link

Question: How can I embed swagger UI? #362

Open dsha256 opened 1 year ago

dsha256 commented 1 year ago

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 1 year ago

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

riley-ashton commented 1 year ago

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