Skip to content
Open
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
59 changes: 59 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# AGENTS.md

## Repository

Go library that embeds a [ReDoc](https://github.com/ReDocly/redoc) UI for OpenAPI/Swagger specs. Provides a core `net/http` handler plus middleware adapters for gin, echo, fiber, and iris.

## Multi-module structure

This is a **multi-module repo**. Each framework adapter is a separate Go module with its own `go.mod`:

```
go.mod # github.com/mvrilo/go-redoc (core, go 1.18)
echo/go.mod # github.com/mvrilo/go-redoc/echo
fiber/go.mod # github.com/mvrilo/go-redoc/fiber
gin/go.mod # github.com/mvrilo/go-redoc/gin
iris/go.mod # github.com/mvrilo/go-redoc/iris
_examples/*/go.mod # standalone example apps
```

**`go test ./...` from root only tests the core module.** Adapter modules must be tested from their own directories.

The echo, fiber, and gin modules use `replace github.com/mvrilo/go-redoc => ../` for local development. The iris module does **not** — it references the published `v0.1.5`.

## Commands

```sh
make test # go test -race ./... (core module only)
make lint # go fmt + go vet + golangci-lint (no .golangci.yml — uses defaults)
make deps # installs golangci-lint
make all # downloads redoc JS from CDN, then lint + test
make assets/redoc.standalone.js # curl the bundled ReDoc v2.5.1 JS
```

To test an adapter module:

```sh
cd echo && go test -race ./...
cd gin && go test -race ./...
# etc.
```

## Architecture

- **`redoc.go`** — the entire core: `Redoc` struct, `Body()` (renders HTML via `text/template`), `Handler()` (serves spec + docs as `http.HandlerFunc`)
- **`assets/index.html`** — Go template; loads ReDoc JS from CDN (`cdn.redoc.ly/redoc/v2.5.1`)
- **`assets/redoc.standalone.js`** — embedded via `//go:embed` into the `JavaScript` var but **not used at runtime** (the HTML template uses the CDN). Inflates binary size (~890 KB) for no benefit.
- **Adapter packages** (`echo/`, `fiber/`, `gin/`, `iris/`) — each ~15 lines, wrapping `Handler()` into framework-specific middleware.
- **`Handler()` panics** on setup errors (spec not found, template render failure). It does not return an error.

## Conventions

- Package naming: `echoredoc`, `fiberredoc`, `ginredoc` — except `iris/` which uses package name `iris` (inconsistent).
- Test framework: `stretchr/testify/assert` with `httptest`.
- Test data: `testdata/spec.json` (Swagger 2.0 Petstore).
- Commit style: loose conventional commits (`feat:`, `fix:`, `chore:`, `refactor:`), lowercase after prefix.

## CI

GitHub Actions on push/PR to `master`: lint job + test job, Go matrix `[1.17, 1.21]`. The `go.mod` minimum is 1.18 — the 1.17 matrix entry is stale.
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.PHONY: all lint test deps

REDOC_PATH=assets/redoc.standalone.js
REDOC_URL=https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js
REDOC_URL=https://cdn.redoc.ly/redoc/v2.5.1/bundles/redoc.standalone.js

.PHONY: all lint test deps $(REDOC_PATH)

all: $(REDOC_PATH) lint test

Expand All @@ -17,4 +17,4 @@ deps:
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

$(REDOC_PATH):
curl -sL -o $(REDOC_PATH) $(REDOC_URL)
curl -sL -o $(REDOC_PATH) $(REDOC_URL)
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,36 @@ app.Use(irisdoc.New(doc))


See [examples](/_examples)


## Configuration Options


```go
r := redoc.Redoc{
SpecFile: "testdata/spec.json",
SpecFS: &spec,
SpecPath: "/openapi.json", // "/openapi.yaml" Title: "Test API",
Description: "Meta Description"
Options: map[string]any{
"disableSearch": true,
"theme": map[string]any{
"colors": map[string]any{"primary": map[string]any{"main": "#297b21"}},
"typography": map[string]any{"headings": map[string]any{"fontWeight": "600"}}
"sidebar": map[string]any{"backgroundColor": "#cae6c6"},
},
},
}
```

`Title` : The head title of your html page - Shown on search engine.

`Description` : The head meta description of your html page - Shown on search engine.

`Options`: redoc option see [Redoc Configuration Documentation](https://github.com/Redocly/redoc/blob/main/docs/config.md)

`SpecFile`: file path to your openapi/swagger file from your project.

`SpecPath`: url path to call your openapi/swagger file from redoc documentation. Must be aligned with your web server configuration.

`DocsPath` : url path to call your generated API documentation. Must be aligned with your web server configuration.
6 changes: 4 additions & 2 deletions assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
<title>{{ .title }}</title>
<meta name="description" content="{{ .description }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">

<style>
body {
margin: 0;
Expand All @@ -14,7 +16,7 @@
</head>
<body>
<div id="main"></div>
<script>{{ .body }}</script>
<script>Redoc.init("{{ .url }}", {}, document.getElementById("main"))</script>
<script src="https://cdn.redoc.ly/redoc/v2.5.1/bundles/redoc.standalone.js"></script>
<script>Redoc.init("{{ .url }}", {{ .options }}, document.getElementById("main"))</script>
</body>
</html>
1,831 changes: 1,830 additions & 1 deletion assets/redoc.standalone.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/mvrilo/go-redoc

go 1.17
go 1.18

require github.com/stretchr/testify v1.8.4

Expand Down
39 changes: 39 additions & 0 deletions redoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
import (
"bytes"
"embed"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
)
Expand All @@ -18,9 +21,11 @@
DocsPath string
SpecPath string
SpecFile string
SpecDir string
SpecFS *embed.FS
Title string
Description string
Options map[string]any

Check failure on line 28 in redoc.go

View workflow job for this annotation

GitHub Actions / test (1.17, ubuntu-latest)

undefined: any
}

// HTML represents the redoc index.html page
Expand All @@ -41,11 +46,21 @@
return nil, err
}

var optionsString = "{}"

var optionsByte, errM = json.Marshal(r.Options)
if errM == nil {
optionsString = string(optionsByte)
} else {
log.Printf("Invalid json options provided, using default options instead.")
}

if err = tpl.Execute(buf, map[string]string{
"body": JavaScript,
"title": r.Title,
"url": r.SpecPath,
"description": r.Description,
"options": optionsString,
}); err != nil {
return nil, err
}
Expand All @@ -69,6 +84,10 @@
r.SpecPath = "/openapi.json"
}

if r.SpecDir == "" {
r.SpecDir = "components"
}

var spec []byte
if r.SpecFS == nil {
spec, err = os.ReadFile(specFile)
Expand Down Expand Up @@ -101,6 +120,26 @@
header.Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(data)
return
}

// load spec files
ext := filepath.Ext(req.URL.Path)
if ext == ".yaml" || ext == ".json" {
header.Set("Content-Type", "application/json")
p := filepath.Join(r.SpecDir, filepath.FromSlash(req.URL.Path))
subSpec, err := os.ReadFile(p)

if err != nil {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("file not found."))
return
}

w.WriteHeader(http.StatusOK)
_, _ = w.Write(subSpec)
return
}

}
}
56 changes: 56 additions & 0 deletions redoc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,59 @@ func TestRedoc(t *testing.T) {
})
})
}

func TestRedocWithOptions(t *testing.T) {
r := redoc.Redoc{
SpecFile: "testdata/spec.json",
SpecFS: &spec,
SpecPath: "/openapi.json", // "/openapi.yaml"
Title: "Test API",
Options: map[string]any{
"disableSearch": true,
"theme": map[string]any{
"colors": map[string]any{"primary": map[string]any{"main": "#297b21"}},
"typography": map[string]any{"headings": map[string]any{"fontWeight": "600"}},
"sidebar": map[string]any{"backgroundColor": "#cae6c6"},
},
},
}

t.Run("Body", func(t *testing.T) {
body, err := r.Body()
assert.NoError(t, err)
assert.Contains(t, string(body), r.Title)
})

t.Run("Handler", func(t *testing.T) {
handler := r.Handler()

t.Run("Spec", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/openapi.json", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))

body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Contains(t, string(body), `"swagger":"2.0"`)
})

t.Run("Docs", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "text/html", resp.Header.Get("Content-Type"))

body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Contains(t, string(body), r.Title)
assert.Contains(t, string(body), `{"disableSearch`)
})
})
}
Loading