swaggerui

package module
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2023 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Embeddable swagger-ui for your Go program

Go Reference Quality Gate Status

This Go module allows you to conveniently serve a swagger UI embedded into your server.

Example


package main

import (
  _ "embed"
  "flag"
  "log"
  "net/http"

  swaggerui "github.com/mwmahlberg/swagger-ui"
)

//go:embed petstore.yaml
var petStore []byte

var bind string

func init() {
  flag.StringVar(&bind, "bind", ":8080", "address to bind to")
}

func main() {

  flag.Parse()

  ui, err := swaggerui.New(swaggerui.Spec(swaggerui.DefaultSpecfileName, petStore))
  if err != nil {
    log.Fatalln(err)
  }

  mux := http.NewServeMux()
  mux.Handle("/api-docs/", http.StripPrefix("/api-docs/", ui))

  mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("dummy api"))
  })

  http.ListenAndServe(bind, mux)
}


Documentation

Overview

swagger-ui provides a simple http.Handler that serves the Swagger UI and the Swagger spec file.

Index

Examples

Constants

View Source
const (
	// DefaultSpecfileName is the default name of the spec file.
	DefaultSpecfileName string = "swagger.yaml"
	// InitializerFilename is the default name of the initializer file.
	InitializerFilename string = "swagger-initializer.js"

	// This is the template for the initializer.js file, which is used to initialize the swagger-ui.
	// Alternatively, you can provide your own initializer by using the InitializerContent option.
	InitializerTemplate string = `` /* 565-byte string literal not displayed */

)

Variables

View Source
var (
	// RegexValidFilename matches a valid filename for a swagger spec file.
	RegexValidFilename = regexp.MustCompile(`(?i)\.(y[a]?ml|json)$`)
)

Functions

This section is empty.

Types

type HandlerOption

type HandlerOption func(*SwaggerUi)

HandlerOptions are used to initialize the handler.

func InitializerContent

func InitializerContent(code []byte) HandlerOption

Instead of using the default "swagger-initializer.js", you can provide your own.

Example
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	swaggerui "github.com/mwmahlberg/swagger-ui"
)

func main() {
	// Error handling ommitted for brevity

	// This will serve an empty initializer
	// Also, the spec file will be named "swagger.yaml" as per the default
	ui, _ := swaggerui.New(swaggerui.InitializerContent([]byte("{}")))

	// Set up a mux and use the handler to serve the UI under /api-docs/
	mux := http.NewServeMux()
	mux.Handle("/api-docs/", http.StripPrefix("/api-docs/", ui))

	// Start a test server
	ts := httptest.NewServer(mux)
	defer ts.Close()

	// Get the initializer
	resp, _ := http.Get(ts.URL + "/api-docs/swagger-initializer.js")

	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()

	fmt.Printf("%s", string(body))
}
Output:
{}

func Spec

func Spec(name string, data []byte) HandlerOption

Sets the name under which the data will be served as a spec file.

Example

Use the Spec option to provide a swagger spec.

package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"

	swaggerui "github.com/mwmahlberg/swagger-ui"
)

func main() {
	// Error handling ommitted for brevity

	// This will serve the spec provided under the default filename "swagger.yaml"
	ui, _ := swaggerui.New(swaggerui.Spec(swaggerui.DefaultSpecfileName, []byte("bar")))

	// Set up a mux and use the handler to serve the UI under /api-docs/
	mux := http.NewServeMux()
	mux.Handle("/api-docs/", http.StripPrefix("/api-docs/", ui))

	// Start a test server
	ts := httptest.NewServer(mux)
	defer ts.Close()

	// Get the spec
	resp, _ := http.Get(ts.URL + "/api-docs/" + swaggerui.DefaultSpecfileName)
	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()

	fmt.Printf("%s: %s", ui.SpecFilename(), string(body))
}
Output:
swagger.yaml: bar

type SetupError

type SetupError struct {
	Cause error
}

func (SetupError) Error

func (s SetupError) Error() string

type SwaggerUi

type SwaggerUi struct {
	Overlay *memfs.FS           `valid:"-"` // The overlay fs that is used to serve the custom spec and initializer
	Static  *fs.FS              `valid:"-"` // The base fs that is used to serve the static files of swagger-ui
	Merged  *merged_fs.MergedFS `valid:"-"` // The overlayfs that is used to serve the swagger-ui
	// contains filtered or unexported fields
}

SwaggerUi is a handler that serves the swagger-ui.

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	swaggerui "github.com/mwmahlberg/swagger-ui"
)

const someYaml string = `
openapi: 3.0.0
info:
	title: Swagger Petstore
	description: This is a sample server Petstore server.
	termsOfService: http://swagger.io/terms/
`

func main() {
	ui, err := swaggerui.New(swaggerui.Spec(swaggerui.DefaultSpecfileName, []byte(someYaml)))
	if err != nil {
		panic(err)
	}
	mux := http.NewServeMux()
	mux.Handle("/api-docs/", http.StripPrefix("/api-docs/", ui))
	ts := httptest.NewServer(mux)
	defer ts.Close()
	resp, err := http.Get(ts.URL + "/api-docs/swagger.yaml")
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.StatusCode)
}
Output:
200

func New

func New(opts ...HandlerOption) (*SwaggerUi, error)

New returns a new SwaggerUi handler.

func (*SwaggerUi) ServeHTTP added in v0.2.0

func (ui *SwaggerUi) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface. It serves the swagger-ui, the spec file and the initializer by using the merged fs via http.FileServer.

func (*SwaggerUi) SpecFilename added in v0.2.0

func (ui *SwaggerUi) SpecFilename() string

Returns the name of the spec file served by the handler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址