Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
32 changes: 32 additions & 0 deletions doc/example_register_exporter_test.go
Original file line number Diff line number Diff line change
@@ -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:
// <title>Orders API</title>
}
32 changes: 32 additions & 0 deletions doc/example_swagger_ui_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package doc_test

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

"github.com/jgolang/api/doc"
)

// printTitleLine prints the <title> 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</title>
}
61 changes: 57 additions & 4 deletions doc/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" stroke="#808080" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4C9 4 8 5.5 8 8v4c0 2-1 3-3 4 2 1 3 2 3 4v4c0 2.5 1 4 4 4"/><path d="M20 4c3 0 4 1.5 4 4v4c0 2 1 3 3 4-2 1-3 2-3 4v4c0 2.5-1 4-4 4"/></svg>`

// swaggerUIHTML pins swagger-ui-dist 5.34.1. When updating the version,
// recompute each integrity hash from the exact file:
//
Expand All @@ -38,7 +90,8 @@ const swaggerUIHTML = `<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>API Docs</title>
<title>%s</title>
<link rel="icon" href="%s">
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.34.1/swagger-ui.css" integrity="sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF" crossorigin="anonymous">
</head>
<body>
Expand Down
116 changes: 114 additions & 2 deletions doc/handlers_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
Expand Down Expand Up @@ -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(`<link rel="icon" href="([^"]*)">`)

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: "<title>Orders API</title>"},
{name: "empty keeps default", title: "", want: "<title>API Docs</title>"},
{name: "markup is escaped", title: "</title><script>x</script>", want: "<title>&lt;/title&gt;&lt;script&gt;x&lt;/script&gt;</title>"},
}
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, "</script>") != 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: `<link rel="icon" href="/static/icon.png">`},
{name: "data uri", favicon: `data:image/svg+xml,<svg a="b&c"></svg>`, want: `<link rel="icon" href="data:image/svg+xml,&lt;svg a=&#34;b&amp;c&#34;&gt;&lt;/svg&gt;">`},
{name: "markup is escaped", favicon: `x"><script>alert(1)</script>`, want: `<link rel="icon" href="x&#34;&gt;&lt;script&gt;alert(1)&lt;/script&gt;">`},
{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, "</script>") != 2 {
t.Fatalf("expected the favicon not to add a script element, got:\n%s", page)
}
})
}
}
22 changes: 22 additions & 0 deletions doc/testdata/swagger-ui-default.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>API Docs</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns=%22http:%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox=%220%200%2032%2032%22%20fill=%22none%22%20stroke=%22%23808080%22%20stroke-width=%223%22%20stroke-linecap=%22round%22%20stroke-linejoin=%22round%22%3E%3Cpath%20d=%22M12%204C9%204%208%205.5%208%208v4c0%202-1%203-3%204%202%201%203%202%203%204v4c0%202.5%201%204%204%204%22%2F%3E%3Cpath%20d=%22M20%204c3%200%204%201.5%204%204v4c0%202%201%203%203%204-2%201-3%202-3%204v4c0%202.5-1%204-4%204%22%2F%3E%3C%2Fsvg%3E">
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.34.1/swagger-ui.css" integrity="sha384-4c3vsE5f+trhFyHrFrLM1fFGUn531NIaC7dcqEWIJdoRQJ5CkJbSuSCwXLpaS1KF" crossorigin="anonymous">
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.34.1/swagger-ui-bundle.js" integrity="sha384-XFYN47VzPiDY6qPtxYKg0nqUeW/upo20xf1j2SUE7gT/i35FJB4cuS/71Iegzk8Z" crossorigin="anonymous"></script>
<script>
window.onload = function() {
window.ui = SwaggerUIBundle({
url: "/openapi.json",
dom_id: "#swagger-ui"
});
};
</script>
</body>
</html>
29 changes: 29 additions & 0 deletions docs/openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<title>`. `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:
Expand Down
Loading