Gin middleware to serve OpenAPI (swagger.json / swagger.yaml) with a modern API reference UI powered by Scalar.
This project was forked from swaggo/gin-swagger.
⸻
- Generate OpenAPI spec with swag
Add comments to your API source code, then run:
go install github.com/swaggo/swag/cmd/swag@latest
swag init -g main.go -o ./docsThis generates docs/swagger.json and docs/swagger.yaml.
⸻
- Install gin-openapi
go get github.com/PeterTakahashi/gin-openapi/openapiui@latest⸻
- Use in your Gin app
package main
import (
"net/http"
"github.com/gin-gonic/gin"
openapiui "github.com/PeterTakahashi/gin-openapi/openapiui"
)
// Example handler
// @Summary Hello world
// @Description returns hello
// @Produce json
// @Success 200 {string} string "hello"
// @Router /hello [get]
func Hello(c *gin.Context) {
c.JSON(http.StatusOK, "hello")
}
func main() {
r := gin.Default()
// Serve API docs at /docs
r.GET("/docs/*any", openapiui.WrapHandler(openapiui.Config{
SpecURL: "/docs/openapi.json",
SpecFilePath: "./docs/swagger.json",
Title: "Example API",
Theme: "light", // or "dark"
}))
// Actual API
r.GET("/hello", Hello)
r.Run(":8080")
}⸻
- Access
• UI → http://localhost:8080/docs
• JSON → http://localhost:8080/docs/openapi.json
⸻
.
├── docs
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── go.mod
├── go.sum
└── main.go
⸻
Instead of serving a static JSON, you can provide your own function:
r.GET("/docs/*any", openapiui.WrapHandler(openapiui.Config{
SpecURL: "/docs/openapi.json",
SpecProvider: func() ([]byte, error) {
return []byte({"openapi":"3.0.0","info":{"title":"Dynamic API","version":"1.0.0"},"paths":{}}), nil
},
}))
⸻
| Field | Type | Default | Description |
|---|---|---|---|
SpecURL |
string | /docs/openapi.json |
Path that UI uses to fetch the spec |
Title |
string | "API Reference" |
Title shown in HTML |
Theme |
string | "light" |
UI theme (light, dark, none) |
SpecFilePath |
string | "" |
Path to pre-generated OpenAPI JSON file |
SpecProvider |
func() ([]byte, error) |
nil |
Function to dynamically provide OpenAPI JSON |
⸻
- Simpler, modern UI powered by Scalar
- Drop-in replacement for gin-swagger if you want Scalar instead of Swagger UI
- Lightweight, no external static assets required (uses CDN by default)