Эх сурвалжийг харах

feat(generator): 支持从HTTP注解中提取路径和方法

在生成OpenAPI文档时,现在会优先使用Protobuf中定义的HTTP注解来确定
请求路径和HTTP方法。如果未指定,则默认使用POST方法和自动生成的路径。此更改增强了与REST API规范的兼容性。
dcsunny 1 сар өмнө
parent
commit
a68c721ff9
1 өөрчлөгдсөн 32 нэмэгдсэн , 3 устгасан
  1. 32 3
      generator/generator.go

+ 32 - 3
generator/generator.go

@@ -17,13 +17,16 @@ package generator
 
 import (
 	"fmt"
-	"google.golang.org/protobuf/types/descriptorpb"
 	"log"
 	"net/url"
 	"regexp"
 	"sort"
 	"strings"
 
+	http2 "net/http"
+
+	"google.golang.org/protobuf/types/descriptorpb"
+
 	"google.golang.org/genproto/googleapis/api/annotations"
 	status_pb "google.golang.org/genproto/googleapis/rpc/status"
 	"google.golang.org/protobuf/compiler/protogen"
@@ -722,9 +725,35 @@ func (g *OpenAPIv3Generator) addPathsToDocumentV3(d *v3.Document, services []*pr
 			if extOperation == nil || extOperation == v3.E_Operation.InterfaceOf(v3.E_Operation.Zero()) {
 				continue
 			}
+			httpOperation := proto.GetExtension(method.Desc.Options(), annotations.E_Http)
+			if httpOperation == nil || httpOperation == annotations.E_Http.InterfaceOf(annotations.E_Http.Zero()) {
+				continue
+			}
 			annotationsCount++
+			_httpOperation := httpOperation.(*annotations.HttpRule)
+			var path string
+			var httpMethod string
+			switch httpRule := _httpOperation.GetPattern().(type) {
+			case *annotations.HttpRule_Post:
+				path = httpRule.Post
+				httpMethod = http2.MethodPost
+			case *annotations.HttpRule_Get:
+				path = httpRule.Get
+				httpMethod = http2.MethodGet
+			case *annotations.HttpRule_Delete:
+				path = httpRule.Delete
+				httpMethod = http2.MethodDelete
+			case *annotations.HttpRule_Put:
+				path = httpRule.Put
+				httpMethod = http2.MethodPut
+			}
+			if path == "" {
+				path = fmt.Sprintf("/api/%s/%s", service.Desc.FullName(), method.GoName)
+			}
 
-			path := fmt.Sprintf("/api/%s/%s", service.Desc.FullName(), method.GoName)
+			if httpMethod == "" {
+				httpMethod = http2.MethodPost
+			}
 
 			defaultHost := proto.GetExtension(service.Desc.Options(), annotations.E_DefaultHost).(string)
 
@@ -734,7 +763,7 @@ func (g *OpenAPIv3Generator) addPathsToDocumentV3(d *v3.Document, services []*pr
 			// Merge any `Operation` annotations with the current
 			proto.Merge(op, extOperation.(*v3.Operation))
 
-			g.addOperationToDocumentV3(d, op, path2, "POST")
+			g.addOperationToDocumentV3(d, op, path2, httpMethod)
 		}
 
 		if annotationsCount > 0 {