Skip to content

Commit 6d8c7c7

Browse files
authored
docs(golang): openapi (#3203)
* docs(golang): openapi * Add dubbo-go samples link
1 parent 23e3cb2 commit 6d8c7c7

File tree

2 files changed

+694
-0
lines changed
  • content
    • en/overview/mannual/golang-sdk/tutorial/rpc
    • zh-cn/overview/mannual/golang-sdk/tutorial/rpc

2 files changed

+694
-0
lines changed
Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
1+
---
2+
description: "Use Dubbo-go's built-in OpenAPI support to automatically generate and expose OpenAPI 3.0 documentation, with Swagger UI and ReDoc for visual API management."
3+
linkTitle: OpenAPI Documentation
4+
title: OpenAPI Documentation Generation & Management
5+
type: docs
6+
weight: 5
7+
---
8+
9+
Dubbo-go provides built-in OpenAPI support that automatically generates OpenAPI 3.0-compliant API documentation for Triple protocol services, with Swagger UI and ReDoc for visual API browsing and debugging.
10+
11+
## Feature Overview
12+
13+
- **Automatic Documentation Generation**: Automatically generates OpenAPI 3.0.1 API documentation based on service interface definitions (protobuf IDL or non-IDL mode)
14+
- **Swagger UI**: Built-in Swagger UI interface for online API browsing and debugging
15+
- **ReDoc**: Built-in ReDoc interface for clean API documentation presentation
16+
- **Multiple Output Formats**: Supports both JSON and YAML output formats
17+
- **Group Management**: Supports organizing services into OpenAPI Groups for managing multiple API versions
18+
- **Static Documentation Generation**: Generate static OpenAPI documentation files at compile time from `.proto` files using the `protoc-gen-triple-openapi` plugin
19+
20+
## Quick Start
21+
22+
### 1. Enable OpenAPI
23+
24+
Enable OpenAPI through the Triple protocol options when creating a Server:
25+
26+
```go
27+
package main
28+
29+
import (
30+
"dubbo.apache.org/dubbo-go/v3/protocol"
31+
triple "dubbo.apache.org/dubbo-go/v3/protocol/triple"
32+
"dubbo.apache.org/dubbo-go/v3/server"
33+
)
34+
35+
func main() {
36+
srv, err := server.NewServer(
37+
server.WithServerProtocol(
38+
protocol.WithTriple(
39+
triple.WithOpenAPI(
40+
triple.OpenAPIEnable(),
41+
),
42+
),
43+
protocol.WithPort(20000),
44+
),
45+
)
46+
if err != nil {
47+
panic(err)
48+
}
49+
// Register services...
50+
srv.Serve()
51+
}
52+
```
53+
54+
Once the service is started, you can access the OpenAPI documentation at the following endpoints:
55+
56+
| Endpoint | Description |
57+
|----------|-------------|
58+
| `http://localhost:20000/dubbo/openapi/swagger-ui/` | Swagger UI interface |
59+
| `http://localhost:20000/dubbo/openapi/redoc/` | ReDoc interface |
60+
| `http://localhost:20000/dubbo/openapi/openapi.json` | OpenAPI JSON format documentation |
61+
| `http://localhost:20000/dubbo/openapi/openapi.yaml` | OpenAPI YAML format documentation |
62+
| `http://localhost:20000/dubbo/openapi/api-docs/{group}.json` | JSON documentation for a specific group |
63+
64+
### 2. Custom Configuration
65+
66+
You can customize various properties of the OpenAPI documentation:
67+
68+
```go
69+
srv, err := server.NewServer(
70+
server.WithServerProtocol(
71+
protocol.WithTriple(
72+
triple.WithOpenAPI(
73+
triple.OpenAPIEnable(),
74+
triple.OpenAPIInfoTitle("My API Service"),
75+
triple.OpenAPIInfoDescription("A service with OpenAPI documentation"),
76+
triple.OpenAPIInfoVersion("1.0.0"),
77+
triple.OpenAPIPath("/custom/openapi"),
78+
),
79+
),
80+
protocol.WithPort(20000),
81+
),
82+
)
83+
```
84+
85+
#### Configuration Options
86+
87+
| Option | Method | Default | Description |
88+
|--------|--------|---------|-------------|
89+
| Enable OpenAPI | `OpenAPIEnable()` | `false` | Enable the OpenAPI feature |
90+
| Document Title | `OpenAPIInfoTitle(title)` | `Dubbo-go OpenAPI` | Title of the API documentation |
91+
| Document Description | `OpenAPIInfoDescription(desc)` | `Dubbo-go OpenAPI` | Description of the API documentation |
92+
| Document Version | `OpenAPIInfoVersion(ver)` | `1.0.0` | Version of the API documentation |
93+
| Base Path | `OpenAPIPath(path)` | `/dubbo/openapi` | URL prefix for OpenAPI endpoints |
94+
| Consumes Media Types | `OpenAPIDefaultConsumesMediaTypes(types...)` | `["application/json"]` | Default Content-Type for request bodies |
95+
| Produces Media Types | `OpenAPIDefaultProducesMediaTypes(types...)` | `["application/json"]` | Default Content-Type for response bodies |
96+
| HTTP Status Codes | `OpenAPIDefaultHttpStatusCodes(codes...)` | `["200","400","500"]` | Default response status codes for each operation |
97+
98+
## Group Management
99+
100+
When you need to expose multiple versions of API documentation within the same application, you can use the OpenAPI group feature. With the `server.WithOpenAPIGroup()` option, you can register different services into different groups:
101+
102+
```go
103+
// Register service to the default group
104+
demo.RegisterGreetServiceHandler(srv, &DemoTripleServerV1{},
105+
server.WithVersion("1.0.0"),
106+
)
107+
108+
// Register service to the "demo-v2" group
109+
demo.RegisterGreetServiceHandler(srv, &DemoTripleServerV2{},
110+
server.WithOpenAPIGroup("demo-v2"),
111+
server.WithVersion("2.0.0"),
112+
)
113+
```
114+
115+
Access group documentation:
116+
117+
- Default group: `http://localhost:20000/dubbo/openapi/api-docs/default.json`
118+
- Specific group: `http://localhost:20000/dubbo/openapi/api-docs/demo-v2.json`
119+
120+
In Swagger UI, groups are displayed as a dropdown list, making it easy to switch between different API documentation groups.
121+
122+
## Non-IDL Mode Support
123+
124+
In addition to protobuf IDL-based services, OpenAPI also supports non-IDL mode services. The framework automatically resolves struct fields and `json` tags via Go reflection to generate corresponding Schema definitions:
125+
126+
```go
127+
type UserService struct{}
128+
129+
type UserRequest struct {
130+
Id int32 `json:"id"`
131+
}
132+
133+
type UserResponse struct {
134+
Id int32 `json:"id"`
135+
Name string `json:"name"`
136+
Age int32 `json:"age"`
137+
}
138+
139+
func (u *UserService) GetUser(ctx context.Context, req *UserRequest) (*UserResponse, error) {
140+
return &UserResponse{
141+
Id: req.Id,
142+
Name: "Alice",
143+
Age: 30,
144+
}, nil
145+
}
146+
147+
func (u *UserService) Reference() string {
148+
return "com.example.UserService"
149+
}
150+
```
151+
152+
After registering the service, OpenAPI automatically generates JSON Schemas for `UserRequest` and `UserResponse`, including field names (from `json` tags) and type mappings.
153+
154+
### Go Type to OpenAPI Schema Mapping
155+
156+
| Go Type | OpenAPI Schema Type |
157+
|---------|---------------------|
158+
| `string` | `string` |
159+
| `bool` | `boolean` |
160+
| `int`, `int32` | `integer` (format: int32) |
161+
| `int64` | `integer` (format: int64) |
162+
| `float32` | `number` (format: float) |
163+
| `float64` | `number` (format: double) |
164+
| `[]T` | `array` (items: schema of T) |
165+
| `map[string]T` | `object` (additionalProperties: schema of T) |
166+
| `time.Time` | `string` (format: date-time) |
167+
| `struct` | `object` (properties: schema of each field) |
168+
169+
## Static Documentation Generation (protoc-gen-triple-openapi)
170+
171+
In addition to runtime-generated online documentation, Dubbo-go provides the `protoc-gen-triple-openapi` tool for generating static OpenAPI documentation files (JSON/YAML) at compile time from `.proto` files. This is useful for integration into CI/CD pipelines or third-party API management platforms.
172+
173+
### Installation
174+
175+
```shell
176+
go install github.com/apache/dubbo-go/tools/protoc-gen-triple-openapi
177+
```
178+
179+
### Usage
180+
181+
Given a `greet.proto` file:
182+
183+
```protobuf
184+
syntax = "proto3";
185+
186+
package greet;
187+
188+
option go_package = "github.com/apache/dubbo-go-samples/rpc/triple/openapi/proto/greet;greet";
189+
190+
message GreetRequest {
191+
string name = 1;
192+
}
193+
194+
message GreetResponse {
195+
string greeting = 1;
196+
}
197+
198+
service GreetService {
199+
rpc Greet(GreetRequest) returns (GreetResponse) {}
200+
}
201+
```
202+
203+
Run the following command to generate OpenAPI documentation:
204+
205+
```shell
206+
protoc --triple-openapi_out=. greet.proto
207+
```
208+
209+
This will generate a `greet.triple.openapi.yaml` file in the current directory with the following content:
210+
211+
```yaml
212+
openapi: 3.0.1
213+
info:
214+
title: Dubbo-go OpenAPI
215+
description: dubbo-go generate OpenAPI docs.
216+
version: v1
217+
servers:
218+
- url: http://0.0.0.0:20000
219+
description: Dubbo-go Default Server
220+
paths:
221+
/greet.GreetService/Greet:
222+
post:
223+
tags:
224+
- greet.GreetService
225+
operationId: Greet
226+
requestBody:
227+
content:
228+
application/json:
229+
schema:
230+
$ref: '#/components/schemas/greet.GreetRequest'
231+
required: true
232+
responses:
233+
"200":
234+
description: OK
235+
content:
236+
application/json:
237+
schema:
238+
$ref: '#/components/schemas/greet.GreetResponse'
239+
"400":
240+
description: Bad Request
241+
"500":
242+
description: Internal Server Error
243+
components:
244+
schemas:
245+
greet.GreetRequest:
246+
type: object
247+
properties:
248+
name:
249+
type: string
250+
greet.GreetResponse:
251+
type: object
252+
properties:
253+
greeting:
254+
type: string
255+
```
256+
257+
## Customizing Swagger UI / ReDoc
258+
259+
You can customize the CDN URLs and UI settings for Swagger UI and ReDoc through `OpenAPISettings`:
260+
261+
```go
262+
triple.WithOpenAPI(
263+
triple.OpenAPIEnable(),
264+
triple.OpenAPISettings(map[string]string{
265+
"swagger-ui.cdn": "https://your-custom-cdn.com/swagger-ui-dist@5.18.2",
266+
"redoc.cdn": "https://your-custom-cdn.com/redoc/latest/bundles",
267+
"swagger-ui.settings.filter": "true",
268+
}),
269+
)
270+
```
271+
272+
Supported settings keys:
273+
274+
| Key | Description | Default |
275+
|-----|-------------|---------|
276+
| `swagger-ui.cdn` | CDN URL for Swagger UI | `https://unpkg.com/swagger-ui-dist@5.18.2` |
277+
| `redoc.cdn` | CDN URL for ReDoc | `https://cdn.redoc.ly/redoc/latest/bundles` |
278+
| `swagger-ui.settings.*` | Additional Swagger UI configuration options (injected into SwaggerUIBundle config) | None |
279+
280+
## Complete Example
281+
282+
Here is a complete example demonstrating various features:
283+
284+
```go
285+
package main
286+
287+
import (
288+
"context"
289+
290+
_ "dubbo.apache.org/dubbo-go/v3/imports"
291+
"dubbo.apache.org/dubbo-go/v3/protocol"
292+
triple "dubbo.apache.org/dubbo-go/v3/protocol/triple"
293+
"dubbo.apache.org/dubbo-go/v3/server"
294+
)
295+
296+
type GreetTripleServer struct{}
297+
298+
func (srv *GreetTripleServer) Greet(ctx context.Context, req *greet.GreetRequest) (*greet.GreetResponse, error) {
299+
return &greet.GreetResponse{Greeting: "Hello, " + req.Name}, nil
300+
}
301+
302+
func main() {
303+
srv, err := server.NewServer(
304+
server.WithServerProtocol(
305+
protocol.WithTriple(
306+
triple.WithOpenAPI(
307+
triple.OpenAPIEnable(),
308+
triple.OpenAPIInfoTitle("OpenAPI Example Service"),
309+
triple.OpenAPIInfoDescription("An example service with OpenAPI documentation"),
310+
triple.OpenAPIInfoVersion("1.0.0"),
311+
),
312+
),
313+
protocol.WithPort(20000),
314+
),
315+
)
316+
if err != nil {
317+
panic(err)
318+
}
319+
320+
if err := greet.RegisterGreetServiceHandler(srv, &GreetTripleServer{}); err != nil {
321+
panic(err)
322+
}
323+
324+
if err := srv.Serve(); err != nil {
325+
panic(err)
326+
}
327+
}
328+
```
329+
330+
After starting, visit `http://localhost:20000/dubbo/openapi/swagger-ui/` to view the Swagger UI documentation.
331+
332+
For the complete example source code, see [dubbo-go-samples OpenAPI example](https://github.com/apache/dubbo-go-samples/tree/main/rpc/triple/openapi).
333+
334+
## Architecture
335+
336+
The core architecture of Dubbo-go OpenAPI consists of the following components:
337+
338+
- **OpenAPIIntegration**: The entry point for OpenAPI integration, responsible for initializing and coordinating all components
339+
- **DefaultService**: The core service that manages service registration, OpenAPI document generation, and caching
340+
- **DefinitionResolver**: Resolves and generates OpenAPI document definitions based on service information
341+
- **SchemaResolver**: Maps Go types to OpenAPI Schemas via Go reflection
342+
- **RequestHandler**: Handles HTTP requests for OpenAPI documents (JSON/YAML format output)
343+
- **SwaggerUIHandler**: Handles Swagger UI page requests
344+
- **RedocHandler**: Handles ReDoc page requests
345+
- **Encoder**: Encodes OpenAPI documents into JSON or YAML format
346+
347+
When a service is registered to the Server, the OpenAPI module collects metadata such as the service's interface name, method information, and request/response types. Upon receiving a documentation request, the DefinitionResolver and SchemaResolver dynamically generate documentation that conforms to the OpenAPI 3.0 specification.

0 commit comments

Comments
 (0)