Go + gRPC 自动生成 Swagger API 文档:3 步实现代码与文档同步

阿里云教程3个月前发布
17 1 0

告别手动维护!
本文将带你 3 步搞定 Go + gRPC 项目的 Swagger 自动化文档。
代码变更自动同步、交互式调试一键开启,开发效率提升 5 倍,生产级方案开箱即用!


1️⃣ 为什么需要自动化 API 文档?

在微服务架构中,API 文档的准确性与实时性 直接影响开发效率、协作体验和系统可维护性。
但传统手动维护文档的方式存在诸多痛点:

痛点

描述

文档与代码不同步

接口更新后文档容易滞后或遗漏

维护成本高

Proto 定义与 Swagger 文档需手动同步

调试效率低

缺乏交互式测试工具

为此,我们希望让 Proto → OpenAPI → Swagger UI 的流程全自动化:
接口定义一改,文档即可自动更新。


2️⃣ 技术选型:为什么选择 Swagger?

✅ 核心优势对比

特性

传统文档方案

Swagger 集成方案

文档生成方式

手动编写

自动从 Proto 生成

调试支持

支持交互式测试界面

协议支持

单一协议

同时支持 gRPC / REST

版本管理

维护困难

与代码变更自动同步

技术栈组成

组件

作用

Proto3

gRPC 接口定义语言

Buf

新一代 Protobuf 构建工具,一次配置,告别繁琐命令

grpc-gateway

gRPC → HTTP 转换层

Swagger UI

可视化交互式 API 文档界面


3️⃣ 项目实战:从零实现 Swagger 集成

环境准备

安装必要工具链:

# 安装 Buf 工具(MacOS)
brew install bufbuild/buf/buf

# 或使用官方安装脚本
curl -sSL https://buf.build/install | bash

安装 Go 插件:

go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@latest

Proto 文件示例与注解规范

文件路径:api/search.proto

syntax = "proto3";

package search;

import "google/api/annotations.proto";

option go_package = "github.com/yourproject/protos/services";

service SearchService {
  rpc SearchPart (SearchRequest) returns (SearchResponse) {
    option (google.api.http) = {
      post: "/v1/search/part"
      body: "*"
    };
  }
}

message SearchRequest {
  string query = 1 [
    (google.api.field_behavior) = REQUIRED,
    (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {
      description: "搜索关键词",
      min_length: 2,
      example: "CPU"
    }
  ];
}

message SearchResponse {
  repeated Part parts = 1;
}

message Part {
  string id = 1;
  string name = 2;
}

⚙️ 使用 Buf 生成 Swagger 文档

① 初始化 Buf 配置

buf init

生成 buf.yaml:

version: v1
deps:
  - buf.build/googleapis/googleapis
  - buf.build/grpc-ecosystem/grpc-gateway
breaking:
  use:
    - FILE
lint:
  use:
    - DEFAULT
generate:
  openapiv2:
    out: gen/openapi
    opt:
      json_names_for_fields: false
      allow_merge: true

② 执行文档生成

buf generate

输出目录示例:

gen/
└── openapi/
    └── search.swagger.json

️ 快速部署 Swagger UI

main.go 示例:

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
	httpSwagger "github.com/swaggo/http-swagger"
)

func main() {
	r := mux.NewRouter()
	r.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
	log.Println("Swagger UI started at: http://localhost:8080/swagger/index.html")
	log.Fatal(http.ListenAndServe(":8080", r))
}

运行:

go run main.go

访问:

http://localhost:8080/swagger/index.html


⚡ 进阶技巧:gRPC + REST 同时启用

mux := runtime.NewServeMux()
err := pb.RegisterSearchServiceHandlerFromEndpoint(
    context.Background(), mux, "localhost:9090", []grpc.DialOption{grpc.WithInsecure()},
)
r.PathPrefix("/api/").Handler(mux)
r.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)

这样,一个服务即可同时支持:

  • 内部调用:gRPC
  • 外部访问:REST + Swagger UI

最终目录结构示例

.
├── api/
│   └── search.proto
├── gen/
│   ├── go/
│   └── openapi/
├── buf.yaml
├── main.go

✅ 总结

  • 通过 Buf + gRPC-Gateway + Swagger 的组合,Go 项目可实现「代码即文档」。
  • 当接口变更时,Swagger 文档自动更新,避免手动维护。
  • 结合 Swagger UI,可直接在线调试接口,大幅提升协作与测试效率。

源码获取

  • GitHub https://github.com/louis-xie-programmer/easyms.es.golang
  • Gitee https://gitee.com/louis_xie/easyms.es.golang

交流与扩展

如果你对 Go 微服务架构、gRPC 深度使用、Swagger 高级技巧或工程化实践感兴趣,
欢迎在评论区留言,我们一起探讨更优雅的 Go 工程解决方案

© 版权声明

相关文章

1 条评论

none
暂无评论...