doc-generate/README.md

251 lines
5.6 KiB
Markdown
Raw Normal View History

2025-09-30 08:16:44 +00:00
# go-doc
[![Go Version](https://img.shields.io/badge/Go-%3E%3D%201.23-blue)](https://go.dev/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
**go-doc** is a standalone tool that converts [go-zero](https://github.com/zeromicro/go-zero) `.api` files into OpenAPI 2.0 (Swagger) specification.
Originally part of the go-zero project, go-doc is now an independent, easy-to-use command-line tool for generating API documentation.
## ✨ Features
- 🚀 **Standalone Binary** - No dependencies on go-zero runtime
- 📝 **Full Swagger 2.0 Support** - Complete OpenAPI specification generation
- 🎯 **Rich Type Support** - Handles structs, arrays, maps, pointers, and nested types
- 🏷️ **Tag-based Configuration** - Support for `json`, `form`, `path`, `header` tags
- 📊 **Advanced Validations** - Range, enum, default, example values
- 🔐 **Security Definitions** - Custom authentication configurations
- 📦 **Multiple Output Formats** - JSON or YAML output
- 🎨 **Definition References** - Optional use of Swagger definitions for cleaner output
## 📦 Installation
### From Source
```bash
git clone https://github.com/danielchan-25/go-doc.git
cd go-doc
go build -o bin/go-doc ./cmd/go-doc
```
### Using Go Install
```bash
go install github.com/danielchan-25/go-doc/cmd/go-doc@latest
```
## 🚀 Quick Start
### Basic Usage
```bash
# Generate JSON swagger file
go-doc -a example/example.api -d output
# Generate YAML swagger file
go-doc -a example/example.api -d output -y
# Specify custom filename
go-doc -a example/example.api -d output -f my-api
```
### Command Line Options
```
Flags:
-a, --api string API file path (required)
-d, --dir string Output directory (required)
-f, --filename string Output filename without extension (optional, defaults to API filename)
-h, --help help for go-doc
-v, --version version for go-doc
-y, --yaml Generate YAML format instead of JSON
```
## 📖 API File Format
### Basic Structure
```go
syntax = "v1"
info (
title: "My API"
description: "API documentation"
version: "v1.0.0"
host: "api.example.com"
basePath: "/v1"
)
type (
UserRequest {
Id int `json:"id,range=[1:10000]"`
Name string `json:"name"`
}
UserResponse {
Id int `json:"id"`
Name string `json:"name"`
}
)
@server (
tags: "user"
)
service MyAPI {
@handler getUser
get /user/:id (UserRequest) returns (UserResponse)
}
```
### Supported Info Properties
- `title` - API title
- `description` - API description
- `version` - API version
- `host` - API host (e.g., "api.example.com")
- `basePath` - Base path (e.g., "/v1")
- `schemes` - Protocols (e.g., "http,https")
- `consumes` - Request content types
- `produces` - Response content types
- `contactName`, `contactURL`, `contactEmail` - Contact information
- `licenseName`, `licenseURL` - License information
- `useDefinitions` - Use Swagger definitions (true/false)
- `wrapCodeMsg` - Wrap response in `{code, msg, data}` structure
- `securityDefinitionsFromJson` - Security definitions in JSON format
### Tag Options
#### JSON Tags
```go
type Example {
// Range validation
Age int `json:"age,range=[1:150]"`
// Default value
Status string `json:"status,default=active"`
// Example value
Email string `json:"email,example=user@example.com"`
// Enum values
Role string `json:"role,options=admin|user|guest"`
// Optional field
Phone string `json:"phone,optional"`
}
```
#### Form Tags
```go
type QueryRequest {
Keyword string `form:"keyword"`
Page int `form:"page,default=1"`
Size int `form:"size,range=[1:100]"`
}
```
#### Path Tags
```go
type PathRequest {
UserId int `path:"userId,range=[1:999999]"`
}
```
#### Header Tags
```go
type HeaderRequest {
Token string `header:"Authorization"`
}
```
## 🔧 Advanced Features
### Security Definitions
```go
info (
securityDefinitionsFromJson: `{
"apiKey": {
"type": "apiKey",
"name": "x-api-key",
"in": "header",
"description": "API Key Authentication"
}
}`
)
@server (
authType: apiKey
)
service MyAPI {
// Routes here will use apiKey authentication
}
```
### Code-Msg Wrapper
```go
info (
wrapCodeMsg: true
bizCodeEnumDescription: "1001-User not found<br>1002-Permission denied"
)
```
Response will be wrapped as:
```json
{
"code": 0,
"msg": "ok",
"data": { /* your actual response */ }
}
```
## 📂 Project Structure
```
go-doc/
├── cmd/
│ └── go-doc/ # Main entry point
│ └── main.go
├── internal/
│ ├── swagger/ # Core swagger generation logic
│ │ ├── swagger.go
│ │ ├── parameter.go
│ │ ├── path.go
│ │ └── ...
│ └── util/ # Internal utilities
│ ├── util.go
│ ├── stringx.go
│ └── pathx.go
├── example/ # Example API files
│ ├── example.api
│ └── example_cn.api
├── go.mod
└── README.md
```
## 🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## 📝 License
This project is licensed under the MIT License.
## 🙏 Acknowledgments
- Original code from [go-zero](https://github.com/zeromicro/go-zero) project
- Built on top of [go-openapi/spec](https://github.com/go-openapi/spec)
## 📧 Contact
For questions or issues, please open an issue on GitHub.
---
Made with ❤️ by extracting and enhancing go-zero's swagger generation capabilities.