diff --git a/README.md b/README.md index 7940905..54d8c25 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,16 @@ func main() { } ``` -`GET /openapi.json` serves the OpenAPI 3 document and `GET /docs` serves Swagger UI pointed at it. Document the body in the shape the request mode expects: the content type itself in plain mode (`doc.Body(CreateTaskRequest{})`), or `doc.Body(envelope.Request[CreateTaskRequest]())` in envelope mode. `envelope.Success[T]()` and `envelope.Error()` document the envelope response mode. +`GET /openapi.json` serves the OpenAPI 3 document and `GET /docs` serves Swagger UI pointed at it. The docs page is titled `API Docs` and ships a generic icon; `doc.WithTitle("Orders API")` and `doc.WithFavicon("/static/orders-icon.png")` set your own (see [Docs page title and icon](docs/openapi.md#docs-page-title-and-icon), which also shows how to pass them through the exporter registry). + +```go +router.Handle("GET", "/docs", doc.SwaggerUIHandler("/openapi.json", + doc.WithTitle("Orders API"), + doc.WithFavicon("/static/orders-icon.png"), +)) +``` + +Document the body in the shape the request mode expects: the content type itself in plain mode (`doc.Body(CreateTaskRequest{})`), or `doc.Body(envelope.Request[CreateTaskRequest]())` in envelope mode. `envelope.Success[T]()` and `envelope.Error()` document the envelope response mode. See [docs/openapi.md](docs/openapi.md) for security schemes, schema tags, response aliases, all route options, and external adapter examples. diff --git a/doc/example_register_exporter_test.go b/doc/example_register_exporter_test.go new file mode 100644 index 0000000..37e266b --- /dev/null +++ b/doc/example_register_exporter_test.go @@ -0,0 +1,32 @@ +package doc_test + +import ( + "fmt" + "net/http" + + "github.com/jgolang/api/doc" +) + +// ordersExporter serves Swagger UI with the service's own title and icon. +type ordersExporter struct{} + +func (ordersExporter) Handler(openAPIURL string) http.HandlerFunc { + return doc.SwaggerUIHandler(openAPIURL, + doc.WithTitle("Orders API"), + doc.WithFavicon("/static/orders-icon.png"), + ) +} + +func ExampleRegisterExporter() { + // A distinct name keeps the default "swagger" exporter untouched. + doc.RegisterExporter("orders-swagger", ordersExporter{}) + + exporter, err := doc.ExporterByName("orders-swagger") + if err != nil { + fmt.Println(err) + return + } + printTitleLine(exporter.Handler("/openapi.json")) + // Output: + // Orders API +} diff --git a/doc/example_swagger_ui_test.go b/doc/example_swagger_ui_test.go new file mode 100644 index 0000000..87f309e --- /dev/null +++ b/doc/example_swagger_ui_test.go @@ -0,0 +1,32 @@ +package doc_test + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + + "github.com/jgolang/api/doc" +) + +// printTitleLine prints the line of the page served by handler. +func printTitleLine(handler http.HandlerFunc) { + res := httptest.NewRecorder() + handler(res, httptest.NewRequest(http.MethodGet, "/docs", nil)) + for _, line := range strings.Split(res.Body.String(), "\n") { + if strings.Contains(line, "<title>") { + fmt.Println(strings.TrimSpace(line)) + } + } +} + +func ExampleSwaggerUIHandler() { + handler := doc.SwaggerUIHandler("/openapi.json", + doc.WithTitle("Orders API"), + doc.WithFavicon("/static/orders-icon.png"), + ) + + printTitleLine(handler) + // Output: + // <title>Orders API +} diff --git a/doc/handlers.go b/doc/handlers.go index 7f79bae..1745f1a 100644 --- a/doc/handlers.go +++ b/doc/handlers.go @@ -3,7 +3,9 @@ package doc import ( "encoding/json" "fmt" + "html" "net/http" + "net/url" ) // OpenAPIHandler returns a handler that serves the docs as OpenAPI JSON. @@ -16,19 +18,69 @@ func OpenAPIHandler(docs *Docs) http.HandlerFunc { } } +// SwaggerUIOption customizes the page served by SwaggerUIHandler. +type SwaggerUIOption func(*swaggerUIConfig) + +type swaggerUIConfig struct { + title string + favicon string +} + +// WithTitle sets the page title shown in the browser tab. The title is +// HTML-escaped. An empty title keeps the default, "API Docs". +func WithTitle(title string) SwaggerUIOption { + return func(config *swaggerUIConfig) { + if title != "" { + config.title = title + } + } +} + +// WithFavicon sets the icon shown in the browser tab, replacing the generic +// default icon. href is a URL ("/static/icon.png") or a data: URI with a PNG, +// SVG or ICO image, and it is HTML-escaped. An empty href keeps the default. +// Percent-encode (url.PathEscape) or base64-encode an SVG data: URI, since a +// raw "#" starts a URL fragment and cuts the image. +func WithFavicon(href string) SwaggerUIOption { + return func(config *swaggerUIConfig) { + if href != "" { + config.favicon = href + } + } +} + // SwaggerUIHandler returns a handler that serves Swagger UI for an OpenAPI URL. // The page loads a pinned swagger-ui-dist release from unpkg, checked with -// Subresource Integrity hashes. -func SwaggerUIHandler(openAPIURL string) http.HandlerFunc { +// Subresource Integrity hashes. Without options the page is titled "API Docs" +// and shows a generic inline icon; WithTitle and WithFavicon change them. +// Options are applied once, when the handler is built; nil options are skipped. +func SwaggerUIHandler(openAPIURL string, opts ...SwaggerUIOption) http.HandlerFunc { + // Percent-encoding keeps raw <, >, ", # and spaces out of the data: URI. + defaultFavicon := "data:image/svg+xml," + url.PathEscape(defaultFaviconSVG) + config := swaggerUIConfig{title: "API Docs", favicon: defaultFavicon} + for _, opt := range opts { + if opt != nil { + opt(&config) + } + } + // html.EscapeString, not html/template: the template URL filter rewrites + // data: URIs to "#ZgotmplZ", and a data: URI is a supported favicon. + title := html.EscapeString(config.title) + favicon := html.EscapeString(config.favicon) // json.Marshal quotes the URL as a JavaScript string literal and escapes // <, > and &, so it cannot end the script element. A string always encodes. encodedURL, _ := json.Marshal(openAPIURL) return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprintf(w, swaggerUIHTML, encodedURL) + fmt.Fprintf(w, swaggerUIHTML, title, favicon, encodedURL) } } +// defaultFaviconSVG is an original "{ }" glyph in a mid gray that stays +// readable on light and dark browser tabs. It is inlined so the page needs no +// extra request. +const defaultFaviconSVG = `` + // swaggerUIHTML pins swagger-ui-dist 5.34.1. When updating the version, // recompute each integrity hash from the exact file: // @@ -38,7 +90,8 @@ const swaggerUIHTML = ` - API Docs + %s + diff --git a/doc/handlers_test.go b/doc/handlers_test.go index e049663..2e30ca9 100644 --- a/doc/handlers_test.go +++ b/doc/handlers_test.go @@ -1,16 +1,20 @@ package doc import ( + "encoding/xml" "net/http" "net/http/httptest" + "net/url" + "os" + "regexp" "strings" "testing" ) -func serveSwaggerUI(t *testing.T, openAPIURL string) string { +func serveSwaggerUI(t *testing.T, openAPIURL string, opts ...SwaggerUIOption) string { t.Helper() res := httptest.NewRecorder() - SwaggerUIHandler(openAPIURL)(res, httptest.NewRequest(http.MethodGet, "/docs", nil)) + SwaggerUIHandler(openAPIURL, opts...)(res, httptest.NewRequest(http.MethodGet, "/docs", nil)) if res.Code != http.StatusOK { t.Fatalf("expected status 200, got %d", res.Code) } @@ -59,3 +63,111 @@ func TestSwaggerUIHandlerEncodesURLForJavaScript(t *testing.T) { }) } } + +func TestSwaggerUIHandlerDefaultPageMatchesGolden(t *testing.T) { + want, err := os.ReadFile("testdata/swagger-ui-default.html") + if err != nil { + t.Fatalf("read golden file: %v", err) + } + + page := serveSwaggerUI(t, "/openapi.json") + + if page != string(want) { + t.Fatalf("default page differs from golden file, got:\n%s", page) + } +} + +func TestSwaggerUIHandlerSkipsNilOption(t *testing.T) { + want := serveSwaggerUI(t, "/openapi.json") + + page := serveSwaggerUI(t, "/openapi.json", nil) + + if page != want { + t.Fatalf("expected a nil option to keep the default page, got:\n%s", page) + } +} + +var faviconHrefPattern = regexp.MustCompile(``) + +func TestSwaggerUIHandlerDefaultFaviconIsInlineSVG(t *testing.T) { + page := serveSwaggerUI(t, "/openapi.json") + + match := faviconHrefPattern.FindStringSubmatch(page) + if match == nil { + t.Fatalf("expected a favicon link, got:\n%s", page) + } + href := match[1] + const prefix = "data:image/svg+xml," + if !strings.HasPrefix(href, prefix) { + t.Fatalf("expected href to start with %q, got %q", prefix, href) + } + if strings.ContainsAny(href, "<>\"# ") { + t.Fatalf("expected href without raw <>\"# or spaces, got %q", href) + } + svg, err := url.PathUnescape(strings.TrimPrefix(href, prefix)) + if err != nil { + t.Fatalf("unescape href: %v", err) + } + var root struct { + XMLName xml.Name + } + if err := xml.Unmarshal([]byte(svg), &root); err != nil { + t.Fatalf("expected well-formed SVG, got %v for %q", err, svg) + } + if root.XMLName.Local != "svg" { + t.Fatalf("expected root element svg, got %q", root.XMLName.Local) + } +} + +func TestSwaggerUIHandlerTitle(t *testing.T) { + tests := []struct { + name string + title string + want string + }{ + {name: "custom", title: "Orders API", want: "Orders API"}, + {name: "empty keeps default", title: "", want: "API Docs"}, + {name: "markup is escaped", title: "", want: "</title><script>x</script>"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + page := serveSwaggerUI(t, "/openapi.json", WithTitle(tt.title)) + + if !strings.Contains(page, tt.want) { + t.Fatalf("expected page to contain %s, got:\n%s", tt.want, page) + } + if strings.Count(page, "") != 2 { + t.Fatalf("expected the title not to add a script element, got:\n%s", page) + } + }) + } +} + +func TestSwaggerUIHandlerFavicon(t *testing.T) { + defaultLink := faviconHrefPattern.FindString(serveSwaggerUI(t, "/openapi.json")) + tests := []struct { + name string + favicon string + want string + }{ + {name: "url", favicon: "/static/icon.png", want: ``}, + {name: "data uri", favicon: `data:image/svg+xml,`, want: ``}, + {name: "markup is escaped", favicon: `x">`, want: ``}, + {name: "empty keeps default", favicon: "", want: defaultLink}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + page := serveSwaggerUI(t, "/openapi.json", WithFavicon(tt.favicon)) + + if !strings.Contains(page, tt.want) { + t.Fatalf("expected page to contain %s, got:\n%s", tt.want, page) + } + if strings.Count(page, `rel="icon"`) != 1 { + t.Fatalf("expected exactly one favicon link, got:\n%s", page) + } + if strings.Count(page, "") != 2 { + t.Fatalf("expected the favicon not to add a script element, got:\n%s", page) + } + }) + } +} diff --git a/doc/testdata/swagger-ui-default.html b/doc/testdata/swagger-ui-default.html new file mode 100644 index 0000000..7c5055e --- /dev/null +++ b/doc/testdata/swagger-ui-default.html @@ -0,0 +1,22 @@ + + + + + + API Docs + + + + +
+ + + + \ No newline at end of file diff --git a/docs/openapi.md b/docs/openapi.md index 5d69249..f31cc46 100644 --- a/docs/openapi.md +++ b/docs/openapi.md @@ -74,6 +74,35 @@ func main() { The `doc` subpackage contains the OpenAPI metadata helpers, schema generation, reusable security schemes, and HTTP handlers for documentation. +## Docs page title and icon + +`doc.SwaggerUIHandler` serves a page titled `API Docs` with a generic inline icon, so the browser tab never shows its blank-page globe. Pass options to make each service's docs tab recognizable: + +```go +router.Handle("GET", "/docs", doc.SwaggerUIHandler("/openapi.json", + doc.WithTitle("Orders API"), + doc.WithFavicon("/static/orders-icon.png"), +)) +``` + +`WithTitle` sets the ``. `WithFavicon` replaces the default icon with a URL or a `data:` URI (PNG, SVG, ICO). Both values are HTML-escaped; an empty value keeps the default. Percent-encode (`url.PathEscape`) or base64-encode an SVG `data:` URI: a raw `#` (as in `fill="#fff"`) starts a URL fragment and cuts the image. + +The built-in `"swagger"` exporter (`doc.ExporterByName("swagger")`) always serves the defaults. To pass options through the exporter registry, register an exporter of your own: + +```go +type ordersExporter struct{} + +func (ordersExporter) Handler(openAPIURL string) http.HandlerFunc { + return doc.SwaggerUIHandler(openAPIURL, doc.WithTitle("Orders API"), doc.WithFavicon("/static/orders-icon.png")) +} + +func init() { + doc.RegisterExporter("orders-swagger", ordersExporter{}) +} +``` + +Registering under `"swagger"` instead replaces the built-in exporter for the whole process. + ## Request and response wrappers Runtime requests use `api.JSONRequest`, whose `content` field is `json.RawMessage` for backward compatibility. For OpenAPI documentation, use typed wrappers so the generator can infer the payload schema: