...

Source file src/github.com/go-openapi/runtime/middleware/rapidoc.go

Documentation: github.com/go-openapi/runtime/middleware

     1  package middleware
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"html/template"
     7  	"net/http"
     8  	"path"
     9  )
    10  
    11  // RapiDocOpts configures the RapiDoc middlewares
    12  type RapiDocOpts struct {
    13  	// BasePath for the UI, defaults to: /
    14  	BasePath string
    15  
    16  	// Path combines with BasePath to construct the path to the UI, defaults to: "docs".
    17  	Path string
    18  
    19  	// SpecURL is the URL of the spec document.
    20  	//
    21  	// Defaults to: /swagger.json
    22  	SpecURL string
    23  
    24  	// Title for the documentation site, default to: API documentation
    25  	Title string
    26  
    27  	// Template specifies a custom template to serve the UI
    28  	Template string
    29  
    30  	// RapiDocURL points to the js asset that generates the rapidoc site.
    31  	//
    32  	// Defaults to https://unpkg.com/rapidoc/dist/rapidoc-min.js
    33  	RapiDocURL string
    34  }
    35  
    36  func (r *RapiDocOpts) EnsureDefaults() {
    37  	common := toCommonUIOptions(r)
    38  	common.EnsureDefaults()
    39  	fromCommonToAnyOptions(common, r)
    40  
    41  	// rapidoc-specifics
    42  	if r.RapiDocURL == "" {
    43  		r.RapiDocURL = rapidocLatest
    44  	}
    45  	if r.Template == "" {
    46  		r.Template = rapidocTemplate
    47  	}
    48  }
    49  
    50  // RapiDoc creates a middleware to serve a documentation site for a swagger spec.
    51  //
    52  // This allows for altering the spec before starting the http listener.
    53  func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler {
    54  	opts.EnsureDefaults()
    55  
    56  	pth := path.Join(opts.BasePath, opts.Path)
    57  	tmpl := template.Must(template.New("rapidoc").Parse(opts.Template))
    58  	assets := bytes.NewBuffer(nil)
    59  	if err := tmpl.Execute(assets, opts); err != nil {
    60  		panic(fmt.Errorf("cannot execute template: %w", err))
    61  	}
    62  
    63  	return serveUI(pth, assets.Bytes(), next)
    64  }
    65  
    66  const (
    67  	rapidocLatest   = "https://unpkg.com/rapidoc/dist/rapidoc-min.js"
    68  	rapidocTemplate = `<!doctype html>
    69  <html>
    70  <head>
    71    <title>{{ .Title }}</title>
    72    <meta charset="utf-8"> <!-- Important: rapi-doc uses utf8 characters -->
    73    <script type="module" src="{{ .RapiDocURL }}"></script>
    74  </head>
    75  <body>
    76    <rapi-doc spec-url="{{ .SpecURL }}"></rapi-doc>
    77  </body>
    78  </html>
    79  `
    80  )
    81  

View as plain text