diff --git a/common/consts/consts.go b/common/consts/consts.go index 2bd92dd..0357119 100644 --- a/common/consts/consts.go +++ b/common/consts/consts.go @@ -53,12 +53,14 @@ const ( const ( CodeGenerationCommentPbHttp = "// Code generated by protoc-gen-http-swagger." + CodeGenerationCommentPbRpc = "// Code generated by protoc-gen-rpc-swagger." CodeGenerationCommentThriftHttp = "// Code generated by thrift-gen-http-swagger." CodeGenerationCommentThriftRpc = "// Code generated by thrift-gen-rpc-swagger." ) const ( PluginNameProtocHttpSwagger = "protoc-gen-http-swagger" + PluginNameProtocRpcSwagger = "protoc-gen-rpc-swagger" PluginNameThriftHttpSwagger = "thrift-gen-http-swagger" PluginNameThriftRpcSwagger = "thrift-gen-rpc-swagger" ) @@ -82,6 +84,7 @@ const ( SchemaObjectType = "object" ComponentSchemaPrefix = "#/components/schemas/" ComponentSchemaSuffixBody = "Body" + ComponentSchemaSuffixForm = "Form" ComponentSchemaSuffixRawBody = "RawBody" ContentTypeJSON = "application/json" @@ -106,4 +109,7 @@ const ( CommentPatternRegexp = `//\s*(.*)|/\*([\s\S]*?)\*/` LinterRulePatternRegexp = `\(-- .* --\)` + + ProtobufValueName = "GoogleProtobufValue" + ProtobufAnyName = "GoogleProtobufAny" ) diff --git a/common/tpl/tpl.go b/common/tpl/tpl.go index 42d24c4..5e2b044 100644 --- a/common/tpl/tpl.go +++ b/common/tpl/tpl.go @@ -169,13 +169,23 @@ func findThriftFile(fileName string) (string, error) { } foundPath := "" + relativePath := fileName + err = filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } - if !info.IsDir() && info.Name() == fileName { - foundPath = path - return filepath.SkipDir + + if !info.IsDir() { + relative, err := filepath.Rel(workingDir, path) + if err != nil { + return err + } + + if relative == relativePath { + foundPath = path + return filepath.SkipDir + } } return nil }) @@ -210,7 +220,282 @@ func initializeGenericClient() genericclient.Client { g, err := generic.JSONThriftGeneric(p) if err != nil { - hlog.Fatal("Failed to create HTTPThriftGeneric:", err) + hlog.Fatal("Failed to create JsonThriftGeneric:", err) + } + var opts []client.Option + opts = append(opts, client.WithTransportProtocol(transport.TTHeader)) + opts = append(opts, client.WithMetaHandler(transmeta.ClientTTHeaderHandler)) + opts = append(opts, client.WithHostPorts(kitexAddr)) + cli, err := genericclient.NewClient("swagger", g, opts...) + if err != nil { + hlog.Fatal("Failed to create generic client:", err) + } + + return cli +} + +func setupSwaggerRoutes(h *server.Hertz) { + h.GET("swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, swagger.URL("/openapi.yaml"))) + + h.GET("/openapi.yaml", func(c context.Context, ctx *app.RequestContext) { + ctx.Header("Content-Type", "application/x-yaml") + ctx.Write(openapiYAML) + }) +} + +func setupProxyRoutes(h *server.Hertz, cli genericclient.Client) { + h.Any("/*ServiceMethod", func(c context.Context, ctx *app.RequestContext) { + serviceMethod := ctx.Param("ServiceMethod") + if serviceMethod == "" { + handleError(ctx, "ServiceMethod not provided", http.StatusBadRequest) + return + } + + bodyBytes := ctx.Request.Body() + + queryMap := formatQueryParams(ctx) + + for k, v := range queryMap { + if strings.HasPrefix(k, "p_") { + c = metainfo.WithPersistentValue(c, k, v) + } else { + c = metainfo.WithValue(c, k, v) + } + } + + c = metainfo.WithBackwardValues(c) + + jReq := string(bodyBytes) + + jRsp, err := cli.GenericCall(c, serviceMethod, jReq) + if err != nil { + hlog.Errorf("GenericCall error: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": err.Error(), + }) + return + } + + result := make(map[string]interface{}) + if err := json.Unmarshal([]byte(jRsp.(string)), &result); err != nil { + hlog.Errorf("Failed to unmarshal response body: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": "Failed to unmarshal response body", + }) + return + } + + m := metainfo.RecvAllBackwardValues(c) + + for key, value := range m { + result[key] = value + } + + respBody, err := json.Marshal(result) + if err != nil { + hlog.Errorf("Failed to marshal response body: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": "Failed to marshal response body", + }) + return + } + + ctx.Data(http.StatusOK, "application/json", respBody) + + }) +} + +func formatQueryParams(ctx *app.RequestContext) map[string]string { + var QueryParams = make(map[string]string) + ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) { + QueryParams[string(key)] = string(value) + }) + return QueryParams +} + +func handleError(ctx *app.RequestContext, errMsg string, statusCode int) { + hlog.Errorf("Error: %s", errMsg) + ctx.JSON(statusCode, map[string]interface{}{ + "error": errMsg, + }) +} +` + +const ServerTemplateRpcPb = `package swagger + +import ( + "context" + _ "embed" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + + "github.com/bytedance/gopkg/cloud/metainfo" + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/app/server" + "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/cloudwego/hertz/pkg/network" + "github.com/cloudwego/hertz/pkg/route" + "github.com/cloudwego/kitex/client" + "github.com/cloudwego/kitex/client/genericclient" + "github.com/cloudwego/kitex/pkg/endpoint" + "github.com/cloudwego/kitex/pkg/generic" + "github.com/cloudwego/kitex/pkg/klog" + "github.com/cloudwego/kitex/pkg/remote" + "github.com/cloudwego/kitex/pkg/remote/trans/detection" + "github.com/cloudwego/kitex/pkg/remote/trans/netpoll" + "github.com/cloudwego/kitex/pkg/remote/trans/nphttp2" + "github.com/cloudwego/kitex/pkg/transmeta" + "github.com/cloudwego/kitex/transport" + "github.com/hertz-contrib/cors" + "github.com/hertz-contrib/swagger" + swaggerFiles "github.com/swaggo/files" +) + +var ( + //go:embed openapi.yaml + openapiYAML []byte + hertzEngine *route.Engine + httpReg = regexp.MustCompile("^(?:GET |POST|PUT|DELE|HEAD|OPTI|CONN|TRAC|PATC)$") +) + +const ( + kitexAddr = "{{.KitexAddr}}" + idlFile = "{{.IdlPath}}" +) + +type MixTransHandlerFactory struct { + OriginFactory remote.ServerTransHandlerFactory +} + +type transHandler struct { + remote.ServerTransHandler +} + +func (t *transHandler) SetInvokeHandleFunc(inkHdlFunc endpoint.Endpoint) { + t.ServerTransHandler.(remote.InvokeHandleFuncSetter).SetInvokeHandleFunc(inkHdlFunc) +} + +func (m MixTransHandlerFactory) NewTransHandler(opt *remote.ServerOption) (remote.ServerTransHandler, error) { + + if hertzEngine == nil { + StartServer() + } + + var kitexOrigin remote.ServerTransHandler + var err error + + if m.OriginFactory != nil { + kitexOrigin, err = m.OriginFactory.NewTransHandler(opt) + } else { + kitexOrigin, err = detection.NewSvrTransHandlerFactory(netpoll.NewSvrTransHandlerFactory(), nphttp2.NewSvrTransHandlerFactory()).NewTransHandler(opt) + } + if err != nil { + return nil, err + } + return &transHandler{ServerTransHandler: kitexOrigin}, nil +} + +func (t *transHandler) OnRead(ctx context.Context, conn net.Conn) error { + c, ok := conn.(network.Conn) + if ok { + pre, _ := c.Peek(4) + if httpReg.Match(pre) { + klog.Info("using Hertz to process request") + err := hertzEngine.Serve(ctx, c) + if err != nil { + err = errors.New(fmt.Sprintf("HERTZ: %s", err.Error())) + } + return err + } + } + + return t.ServerTransHandler.OnRead(ctx, conn) +} + +func StartServer() { + h := server.Default() + h.Use(cors.Default()) + + cli := initializeGenericClient() + setupSwaggerRoutes(h) + setupProxyRoutes(h, cli) + + hlog.Info("Swagger UI is available at: http://" + kitexAddr + "/swagger/index.html") + err := h.Engine.Init() + if err != nil { + panic(err) + } + + hertzEngine = h.Engine +} + +func findPbFile(fileName string) (string, error) { + workingDir, err := os.Getwd() + if err != nil { + return "", err + } + + foundPath := "" + relativePath := fileName + + err = filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + relative, err := filepath.Rel(workingDir, path) + if err != nil { + return err + } + + if relative == relativePath { + foundPath = path + return filepath.SkipDir + } + } + return nil + }) + + if err == nil && foundPath != "" { + return foundPath, nil + } + + parentDir := filepath.Dir(workingDir) + for parentDir != "/" && parentDir != "." && parentDir != workingDir { + filePath := filepath.Join(parentDir, fileName) + if _, err := os.Stat(filePath); err == nil { + return filePath, nil + } + workingDir = parentDir + parentDir = filepath.Dir(parentDir) + } + + return "", errors.New("proto file not found: " + fileName) +} + +func initializeGenericClient() genericclient.Client { + pbFile, err := findPbFile(idlFile) + if err != nil { + hlog.Fatal("Failed to locate Proto file:", err) + } + + dOpts := proto.Options{} + p, err := generic.NewPbFileProviderWithDynamicGo(pbFile, context.Background(), dOpts) + if err != nil { + hlog.Fatal("Failed to create PbFileProvider:", err) + } + + g, err := generic.JSONPbGeneric(p) + if err != nil { + hlog.Fatal("Failed to create JsonPbGeneric:", err) } var opts []client.Option opts = append(opts, client.WithTransportProtocol(transport.TTHeader)) diff --git a/licenses/LICENSE-gopkg.txt b/licenses/LICENSE-gopkg.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/licenses/LICENSE-gopkg.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/LICENSE-hertz.txt b/licenses/LICENSE-hertz.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/licenses/LICENSE-hertz.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/LICENSE-kitex.txt b/licenses/LICENSE-kitex.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/licenses/LICENSE-kitex.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/protoc-gen-http-swagger/example/swagger/openapi.yaml b/protoc-gen-http-swagger/example/swagger/openapi.yaml index edb24c0..3928ee2 100644 --- a/protoc-gen-http-swagger/example/swagger/openapi.yaml +++ b/protoc-gen-http-swagger/example/swagger/openapi.yaml @@ -24,14 +24,7 @@ paths: content: application/json: schema: - type: object - properties: - body: - type: string - description: 'field: body描述' - body1: - type: string - description: 'field: body1描述' + $ref: '#/components/schemas/BodyReqBody' responses: "200": description: HelloResp描述 @@ -54,32 +47,10 @@ paths: content: multipart/form-data: schema: - title: Hello - request - required: - - form1 - type: object - properties: - form1: - title: this is an override field schema title - maxLength: 255 - type: string - form2: - $ref: '#/components/schemas/FormReq_InnerForm' - description: Hello - request + $ref: '#/components/schemas/FormReqForm' application/x-www-form-urlencoded: schema: - title: Hello - request - required: - - form1 - type: object - properties: - form1: - title: this is an override field schema title - maxLength: 255 - type: string - form2: - $ref: '#/components/schemas/FormReq_InnerForm' - description: Hello - request + $ref: '#/components/schemas/FormReqForm' responses: "200": description: HelloResp描述 @@ -204,6 +175,28 @@ paths: - url: http://127.0.0.1:8888 components: schemas: + BodyReqBody: + type: object + properties: + body: + type: string + description: 'field: body描述' + body1: + type: string + description: 'field: body1描述' + FormReqForm: + title: Hello - request + required: + - form1 + type: object + properties: + form1: + title: this is an override field schema title + maxLength: 255 + type: string + form2: + $ref: '#/components/schemas/FormReq_InnerForm' + description: Hello - request FormReq_InnerForm: type: object properties: diff --git a/protoc-gen-http-swagger/generator/openapi_gen.go b/protoc-gen-http-swagger/generator/openapi_gen.go index deac497..4f2262f 100644 --- a/protoc-gen-http-swagger/generator/openapi_gen.go +++ b/protoc-gen-http-swagger/generator/openapi_gen.go @@ -92,7 +92,7 @@ func NewOpenAPIGenerator(plugin *protogen.Plugin, conf Configuration, inputFiles // Run runs the generator. func (g *OpenAPIGenerator) Run(outputFile *protogen.GeneratedFile) error { d := g.buildDocument() - bytes, err := d.YAMLValue("Generated with protoc-gen-http-swagger\n" + consts.InfoURL + consts.PluginNameProtocHttpSwagger) + bytes, err := d.YAMLValue("Generated with " + consts.PluginNameProtocHttpSwagger + "\n" + consts.InfoURL + consts.PluginNameProtocHttpSwagger) if err != nil { return fmt.Errorf("failed to marshal yaml: %s", err.Error()) } @@ -461,32 +461,51 @@ func (g *OpenAPIGenerator) buildOperation( var RequestBody *openapi.RequestBodyOrReference if methodName != consts.HttpMethodGet && methodName != consts.HttpMethodHead && methodName != consts.HttpMethodDelete { - bodySchema := g.getSchemaByOption(inputMessage, api.E_Body) - formSchema := g.getSchemaByOption(inputMessage, api.E_Form) - rawBodySchema := g.getSchemaByOption(inputMessage, api.E_RawBody) - var additionalProperties []*openapi.NamedMediaType + bodySchema := g.getSchemaByOption(inputMessage, api.E_Body) + if len(bodySchema.Properties.AdditionalProperties) > 0 { + + bodyRefSchema := &openapi.NamedSchemaOrReference{ + Name: g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixBody, + Value: &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: bodySchema}}, + } + + bodyRef := consts.ComponentSchemaPrefix + g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixBody + + g.addSchemaToDocument(d, bodyRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeJSON, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Oneof: &openapi.SchemaOrReference_Schema{ - Schema: bodySchema, + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: bodyRef}, }, }, }, }) } + formSchema := g.getSchemaByOption(inputMessage, api.E_Form) + if len(formSchema.Properties.AdditionalProperties) > 0 { + formRefSchema := &openapi.NamedSchemaOrReference{ + Name: g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixForm, + Value: &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: formSchema}}, + } + + formRef := consts.ComponentSchemaPrefix + g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixForm + + g.addSchemaToDocument(d, formRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeFormMultipart, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Oneof: &openapi.SchemaOrReference_Schema{ - Schema: formSchema, + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: formRef}, }, }, }, @@ -496,21 +515,32 @@ func (g *OpenAPIGenerator) buildOperation( Name: consts.ContentTypeFormURLEncoded, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Oneof: &openapi.SchemaOrReference_Schema{ - Schema: formSchema, + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: formRef}, }, }, }, }) } + rawBodySchema := g.getSchemaByOption(inputMessage, api.E_RawBody) + if len(rawBodySchema.Properties.AdditionalProperties) > 0 { + rawBodyRefSchema := &openapi.NamedSchemaOrReference{ + Name: g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixRawBody, + Value: &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: rawBodySchema}}, + } + + rawBodyRef := consts.ComponentSchemaPrefix + g.reflect.formatMessageName(inputMessage.Desc) + consts.ComponentSchemaSuffixRawBody + + g.addSchemaToDocument(d, rawBodyRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeRawBody, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Oneof: &openapi.SchemaOrReference_Schema{ - Schema: rawBodySchema, + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: rawBodyRef}, }, }, }, diff --git a/protoc-gen-http-swagger/generator/reflector.go b/protoc-gen-http-swagger/generator/reflector.go index 5f1d214..dda488a 100644 --- a/protoc-gen-http-swagger/generator/reflector.go +++ b/protoc-gen-http-swagger/generator/reflector.go @@ -37,6 +37,7 @@ import ( "log" "strings" + "github.com/hertz-contrib/swagger-generate/common/consts" common "github.com/hertz-contrib/swagger-generate/common/utils" "github.com/hertz-contrib/swagger-generate/idl/protobuf/openapi" wk "github.com/hertz-contrib/swagger-generate/protoc-gen-http-swagger/generator/wellknown" @@ -44,11 +45,6 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" ) -const ( - protobufValueName = "GoogleProtobufValue" - protobufAnyName = "GoogleProtobufAny" -) - type OpenAPIReflector struct { conf Configuration requiredSchemas []string // Names of schemas which are used through references. @@ -79,9 +75,9 @@ func (r *OpenAPIReflector) formatMessageName(message protoreflect.MessageDescrip name := r.getMessageName(message) if !*r.conf.FQSchemaNaming { if typeName == ".google.protobuf.Value" { - name = protobufValueName + name = consts.ProtobufValueName } else if typeName == ".google.protobuf.Any" { - name = protobufAnyName + name = consts.ProtobufAnyName } } diff --git a/protoc-gen-rpc-swagger/README.md b/protoc-gen-rpc-swagger/README.md new file mode 100644 index 0000000..87e3abc --- /dev/null +++ b/protoc-gen-rpc-swagger/README.md @@ -0,0 +1,72 @@ +# protoc-gen-rpc-swagger + +English | [中文](README_CN.md) + +This is a plugin for generating RPC Swagger documentation and providing Swagger-UI access and debugging for [cloudwego/cwgo](https://github.com/cloudwego/cwgo) & [kitex](https://github.com/cloudwego/kitex). + +## Installation + +```sh +# Install from the official repository +git clone https://github.com/hertz-contrib/swagger-generate +cd protoc-gen-rpc-swagger +go install +# Direct installation +go install github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger@latest +``` + +## Usage + +### Generate Swagger Documentation + +```sh +protoc --rpc-swagger_out=swagger -I idl idl/hello.proto +``` +Here’s the translation of the given section into English: + +### Add Option During Kitex Server Initialization + +```sh +svr := api.NewServer(new(HelloImpl), server.WithTransHandlerFactory(&swagger.MixTransHandlerFactory{})) +``` + +### Access Swagger-UI (Kitex service must be running for debugging) + +```sh +http://127.0.0.1:8888/swagger/index.html +``` + +## Instructions + +### Generation Instructions +1. The plugin will generate Swagger documentation and simultaneously generate an HTTP (Hertz) service to provide access to and debugging of the Swagger documentation. +2. All RPC methods will be converted into HTTP `POST` methods. The request parameters correspond to the Request body, and the content type is in `application/json` format. The response follows the same format. +3. Annotations can be used to supplement the Swagger documentation with information, such as `openapi.operation`, `openapi.property`, `openapi.schema`, `api.base_domain`, `api.baseurl`. +4. To use annotations like `openapi.operation`, `openapi.property`, `openapi.schema`, and `openapi.document`, you need to reference [annotations.proto](example/idl/openapi/annotations.proto). + +### Debugging Instructions +1. Ensure that the proto files, `openapi.yaml`, and `swagger.go` are in the same directory. +2. By default, the HTTP service runs on the same port as the RPC service, with protocol sniffing implemented. +3. To access the Swagger documentation and debug the RPC service, you must add "server.WithTransHandlerFactory(&swagger.MixTransHandlerFactory{})" during Kitex Server initialization. + +### Metadata Transmission +1. Metadata transmission is supported. The plugin generates a `ttheader` query parameter for each method by default, used for passing metadata. The format should comply with JSON, like `{"p_k":"p_v","k":"v"}`. +2. Single-hop metadata transmission uses the format `"key":"value"`. +3. Persistent metadata transmission uses the format `"p_key":"value"` and requires the prefix `p_`. +4. Reverse metadata transmission is supported. If set, metadata will be included in the response and returned in the `"key":"value"` format. +5. For more details on using metadata, refer to [Metainfo](https://www.cloudwego.io/docs/kitex/tutorials/advanced-feature/metainfo/). + +## Supported Annotations + +| Annotation | Component | Description | +|---------------------|-----------|----------------------------------------------------------------------| +| `openapi.operation` | Method | Supplements `operation` in `pathItem` | +| `openapi.property` | Field | Supplements `property` in `schema` | +| `openapi.schema` | Message | Supplements `schema` in `requestBody` and `response` | +| `openapi.document` | Document | Supplements the Swagger documentation | +| `api.base_domain` | Service | Specifies the service `url` corresponding to the `server` | +| `api.baseurl` | Method | Specifies the method’s `url` corresponding to `server` in `pathItem` | + +## More Information + +For more usage examples, please refer to the [examples](example/idl/hello.proto). \ No newline at end of file diff --git a/protoc-gen-rpc-swagger/README_CN.md b/protoc-gen-rpc-swagger/README_CN.md new file mode 100644 index 0000000..ac6aa2a --- /dev/null +++ b/protoc-gen-rpc-swagger/README_CN.md @@ -0,0 +1,77 @@ +# protoc-gen-rpc-swagger + +[English](README.md) | 中文 + +适用于 [cloudwego/cwgo](https://github.com/cloudwego/cwgo) & [kitex](https://github.com/cloudwego/kitex) 的 rpc swagger 文档生成及 swagger-ui 访问调试插件。 + +## 安装 + +```sh +# 官方仓库安装 +git clone https://github.com/hertz-contrib/swagger-generate +cd protoc-gen-rpc-swagger +go install +# 直接安装 +go install github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger@latest +``` + +## 使用 + +### 生成 swagger 文档 + +```sh +protoc --rpc-swagger_out=swagger -I idl idl/hello.proto +``` +### 在 Kitex Server 初始化中添加 option + +```sh + +svr := api.NewServer(new(HelloImpl), server.WithTransHandlerFactory(&swagger.MixTransHandlerFactory{})) + +``` + +### 访问 swagger-ui (调试需启动 Kitex 服务) + +```sh + +http://127.0.0.1:8888/swagger/index.html +``` + +## 使用说明 + +### 生成说明 +1. 插件会生成 swagger 文档,同时生成一个 http (Hertz) 服务, 用于提供 swagger 文档的访问及调试。 +2. 所有的 rpc 方法会转换成 http 的 `post` 方法,请求参数对应 Request body, content 类型为 `application/json` 格式,返回值同上。 +3. 可通过注解来补充 swagger 文档的信息,如 `openapi.operation`, `openapi.property`, `openapi.schema`, `api.base_domain`, `api.baseurl`。 +4. 如需使用`openapi.operation`, `openapi.property`, `openapi.schema`, `openpai.document` 注解,需引用 [annotations.proto](example/idl/openapi/annotations.proto)。 + +### 调试说明 +1. 需保证 proto 文件与 `openapi.yaml`、 `swagger.go` 在同一目录下。 +2. http 服务默认和 rpc 服务在一个端口, 通过嗅探协议实现。 +3. swagger 文档的访问及 rpc 服务的调试需在 Kitex Server 初始化中加入 "server.WithTransHandlerFactory(&swagger.MixTransHandlerFactory{})"。 + +### 元信息传递 +1. 支持元信息传递, 插件默认为每个方法生成一个`ttheader`的查询参数, 用于传递元信息, 格式需满足 json 格式, 如`{"p_k":"p_v","k":"v"}`。 +2. 单跳透传元信息, 格式为 `"key":"value"`。 +3. 持续透传元信息, 格式为 `"p_key":"value"`, 需添加前缀`p_`。 +4. 支持反向透传元信息, 若设置则可在返回值中查看到元信息, 返回通过`"key":"value"`的格式附加在响应中。 +5. 更多使用元信息可参考 [Metainfo](https://www.cloudwego.io/zh/docs/kitex/tutorials/advanced-feature/metainfo/)。 + +## 支持的注解 + +| 注解 | 使用组件 | 说明 | +|---------------------|----------|-------------------------------------------------------| +| `openapi.operation` | Method | 用于补充 `pathItem` 的 `operation` | +| `openapi.property` | Field | 用于补充 `schema` 的 `property` | +| `openapi.schema` | Message | 用于补充 `requestBody` 和 `response` 的 `schema` | +| `openapi.document` | Document | 用于补充 swagger 文档 | +| `api.base_domain` | Service | 对应 `server` 的 `url`, 用于指定 service 服务的 url | +| `api.baseurl` | Method | 对应 `pathItem` 的 `server` 的 `url`, 用于指定单个 method 的 url | + +## 更多信息 + +更多的使用方法请参考 [示例](example/idl/hello.proto) + + + + diff --git a/protoc-gen-rpc-swagger/example/idl/api.proto b/protoc-gen-rpc-swagger/example/idl/api.proto new file mode 100644 index 0000000..da6585c --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/api.proto @@ -0,0 +1,76 @@ +// idl/api.proto; 注解拓展 +syntax = "proto2"; + +package api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "/api"; + +extend google.protobuf.FieldOptions { + optional string raw_body = 50101; + optional string query = 50102; + optional string header = 50103; + optional string cookie = 50104; + optional string body = 50105; + optional string path = 50106; + optional string vd = 50107; + optional string form = 50108; + optional string js_conv = 50109; + optional string file_name = 50110; + optional string none = 50111; + + // 50131~50160 used to extend field option by hz + optional string form_compatible = 50131; + optional string js_conv_compatible = 50132; + optional string file_name_compatible = 50133; + optional string none_compatible = 50134; + // 50135 is reserved to vt_compatible + // optional FieldRules vt_compatible = 50135; + + optional string go_tag = 51001; +} + +extend google.protobuf.MethodOptions { + optional string get = 50201; + optional string post = 50202; + optional string put = 50203; + optional string delete = 50204; + optional string patch = 50205; + optional string options = 50206; + optional string head = 50207; + optional string any = 50208; + optional string gen_path = 50301; // The path specified by the user when the client code is generated, with a higher priority than api_version + optional string api_version = 50302; // Specify the value of the :version variable in path when the client code is generated + optional string tag = 50303; // rpc tag, can be multiple, separated by commas + optional string name = 50304; // Name of rpc + optional string api_level = 50305; // Interface Level + optional string serializer = 50306; // Serialization method + optional string param = 50307; // Whether client requests take public parameters + optional string baseurl = 50308; // Baseurl used in ttnet routing + optional string handler_path = 50309; // handler_path specifies the path to generate the method + + // 50331~50360 used to extend method option by hz + optional string handler_path_compatible = 50331; // handler_path specifies the path to generate the method +} + +extend google.protobuf.EnumValueOptions { + optional int32 http_code = 50401; + +// 50431~50460 used to extend enum option by hz +} + +extend google.protobuf.ServiceOptions { + optional string base_domain = 50402; + + // 50731~50760 used to extend service option by hz + optional string base_domain_compatible = 50731; +} + +extend google.protobuf.MessageOptions { + // optional FieldRules msg_vt = 50111; + + optional string reserve = 50830; + // 550831 is reserved to msg_vt_compatible + // optional FieldRules msg_vt_compatible = 50831; +} diff --git a/protoc-gen-rpc-swagger/example/idl/google/protobuf/any.proto b/protoc-gen-rpc-swagger/example/idl/google/protobuf/any.proto new file mode 100644 index 0000000..eff44e5 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/google/protobuf/any.proto @@ -0,0 +1,162 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/known/anypb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "AnyProto"; +option java_multiple_files = true; +option objc_class_prefix = "GPB"; +option csharp_namespace = "Google.Protobuf.WellKnownTypes"; + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// // or ... +// if (any.isSameTypeAs(Foo.getDefaultInstance())) { +// foo = any.unpack(Foo.getDefaultInstance()); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } +// ... +// foo := &pb.Foo{} +// if err := any.UnmarshalTo(foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// JSON +// ==== +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +message Any { + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. As of May 2023, there are no widely used type server + // implementations and no plans to implement one. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + string type_url = 1; + + // Must be a valid serialized protocol buffer of the above specified type. + bytes value = 2; +} diff --git a/protoc-gen-rpc-swagger/example/idl/google/protobuf/descriptor.proto b/protoc-gen-rpc-swagger/example/idl/google/protobuf/descriptor.proto new file mode 100644 index 0000000..0350c92 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/google/protobuf/descriptor.proto @@ -0,0 +1,1218 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +syntax = "proto2"; + +package google.protobuf; + +option go_package = "google.golang.org/protobuf/types/descriptorpb"; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.Reflection"; +option objc_class_prefix = "GPB"; +option cc_enable_arenas = true; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// The full set of known editions. +enum Edition { + // A placeholder for an unknown edition value. + EDITION_UNKNOWN = 0; + + // Legacy syntax "editions". These pre-date editions, but behave much like + // distinct editions. These can't be used to specify the edition of proto + // files, but feature definitions must supply proto2/proto3 defaults for + // backwards compatibility. + EDITION_PROTO2 = 998; + EDITION_PROTO3 = 999; + + // Editions that have been released. The specific values are arbitrary and + // should not be depended on, but they will always be time-ordered for easy + // comparison. + EDITION_2023 = 1000; + + // Placeholder editions for testing feature resolution. These should not be + // used or relied on outside of tests. + EDITION_1_TEST_ONLY = 1; + EDITION_2_TEST_ONLY = 2; + EDITION_99997_TEST_ONLY = 99997; + EDITION_99998_TEST_ONLY = 99998; + EDITION_99999_TEST_ONLY = 99999; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2", "proto3", and "editions". + // + // If `edition` is present, this value must be "editions". + optional string syntax = 12; + + // The edition of the proto file. + optional Edition edition = 14; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + + optional ExtensionRangeOptions options = 3; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; + + // Range of reserved tag numbers. Reserved tag numbers may not be used by + // fields or extension ranges in the same message. Reserved ranges may + // not overlap. + message ReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Exclusive. + } + repeated ReservedRange reserved_range = 9; + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + repeated string reserved_name = 10; +} + +message ExtensionRangeOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + message Declaration { + // The extension number declared within the extension range. + optional int32 number = 1; + + // The fully-qualified name of the extension field. There must be a leading + // dot in front of the full name. + optional string full_name = 2; + + // The fully-qualified type name of the extension field. Unlike + // Metadata.type, Declaration.type must have a leading dot for messages + // and enums. + optional string type = 3; + + // If true, indicates that the number is reserved in the extension range, + // and any extension field with the number will fail to compile. Set this + // when a declared extension field is deleted. + optional bool reserved = 5; + + // If true, indicates that the extension must be defined as repeated. + // Otherwise the extension must be defined as optional. + optional bool repeated = 6; + + reserved 4; // removed is_repeated + } + + // For external users: DO NOT USE. We are in the process of open sourcing + // extension declaration and executing internal cleanups before it can be + // used externally. + repeated Declaration declaration = 2 [retention = RETENTION_SOURCE]; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The verification state of the extension range. + enum VerificationState { + // All the extensions of the range must be declared. + DECLARATION = 0; + UNVERIFIED = 1; + } + + // The verification state of the range. + // TODO: flip the default to DECLARATION once all empty ranges + // are marked as UNVERIFIED. + optional VerificationState verification = 3 [default = UNVERIFIED]; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + // Tag-delimited aggregate. + // Group type is deprecated and not supported after google.protobuf. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. In Editions, the group wire format + // can be enabled via the `message_encoding` feature. + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + } + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REPEATED = 3; + // The required label is only allowed in google.protobuf. In proto3 and Editions + // it's explicitly prohibited. In Editions, the `field_presence` feature + // can be used to get this behavior. + LABEL_REQUIRED = 2; + } + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + optional int32 oneof_index = 9; + + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + optional string json_name = 10; + + optional FieldOptions options = 8; + + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must be belong to a oneof to + // signal to old proto3 clients that presence is tracked for this field. This + // oneof is known as a "synthetic" oneof, and this field must be its sole + // member (each proto3 optional field gets its own synthetic oneof). Synthetic + // oneofs exist in the descriptor only, and do not generate any API. Synthetic + // oneofs must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + optional bool proto3_optional = 17; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; + optional OneofOptions options = 2; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; + + // Range of reserved numeric values. Reserved values may not be used by + // entries in the same enum. Reserved ranges may not overlap. + // + // Note that this is distinct from DescriptorProto.ReservedRange in that it + // is inclusive such that it can appropriately represent the entire int32 + // domain. + message EnumReservedRange { + optional int32 start = 1; // Inclusive. + optional int32 end = 2; // Inclusive. + } + + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + repeated EnumReservedRange reserved_range = 4; + + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + repeated string reserved_name = 5; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [default = false]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [default = false]; +} + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Objective-C plugin) and your project website (if available) -- there's no +// need to explain how you intend to use them. Usually you only need one +// extension number. You can declare multiple options with only one extension +// number by putting them in a sub-message. See the Custom Options section of +// the docs for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + // Controls the name of the wrapper Java class generated for the .proto file. + // That class will always contain the .proto file's getDescriptor() method as + // well as any top-level extensions defined in the .proto file. + // If java_multiple_files is disabled, then all the other classes from the + // .proto file will be nested inside the single wrapper outer class. + optional string java_outer_classname = 8; + + // If enabled, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the wrapper class + // named by java_outer_classname. However, the wrapper class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default = false]; + + // This option does nothing. + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [default = false]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default = SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default = false]; + optional bool java_generic_services = 17 [default = false]; + optional bool py_generic_services = 18 [default = false]; + optional bool php_generic_services = 42 [default = false]; + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [default = false]; + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [default = true]; + + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + optional string objc_class_prefix = 36; + + // Namespace for generated classes; defaults to the package. + optional string csharp_namespace = 37; + + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + optional string swift_prefix = 39; + + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + optional string php_class_prefix = 40; + + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + optional string php_namespace = 41; + + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + optional string php_metadata_namespace = 44; + + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + optional string ruby_package = 45; + + // Any features defined in the specific edition. + optional FeatureSet features = 50; + + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. + // See the documentation for the "Options" section above. + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default = false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default = false]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [default = false]; + + reserved 4, 5, 6; + + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + // + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + optional bool map_entry = 7; + + reserved 8; // javalite_serializable + reserved 9; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // + // This should only be used as a temporary measure against broken builds due + // to the change in behavior for JSON field name conflicts. + // + // TODO This is legacy behavior we plan to remove once downstream + // teams have had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 11 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 12; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is only implemented to support use of + // [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + // type "bytes" in the open source release -- sorry, we'll try to include + // other types in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + // The option [ctype=CORD] may be applied to a non-repeated field of type + // "bytes". It indicates that in C++, the data should be stored in a Cord + // instead of a string. For very large strings, this may reduce memory + // fragmentation. It may also allow better performance when parsing from a + // Cord, or when parsing with aliasing enabled, as the parsed Cord may then + // alias the original buffer. + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. This option is prohibited in + // Editions, but the `repeated_field_encoding` feature can be used to control + // the behavior. + optional bool packed = 2; + + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + optional JSType jstype = 6 [default = JS_NORMAL]; + enum JSType { + // Use the default type. + JS_NORMAL = 0; + + // Use JavaScript strings. + JS_STRING = 1; + + // Use JavaScript numbers. + JS_NUMBER = 2; + } + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outer message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + // + // As of May 2022, lazy verifies the contents of the byte stream during + // parsing. An invalid byte stream will cause the overall parsing to fail. + optional bool lazy = 5 [default = false]; + + // unverified_lazy does no correctness checks on the byte stream. This should + // only be used where lazy with verification is prohibitive for performance + // reasons. + optional bool unverified_lazy = 15 [default = false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default = false]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default = false]; + + // Indicate that the field value should not be printed out when using debug + // formats, e.g. when the field contains sensitive credentials. + optional bool debug_redact = 16 [default = false]; + + // If set to RETENTION_SOURCE, the option will be omitted from the binary. + // Note: as of January 2023, support for this is in progress and does not yet + // have an effect (b/264593489). + enum OptionRetention { + RETENTION_UNKNOWN = 0; + RETENTION_RUNTIME = 1; + RETENTION_SOURCE = 2; + } + + optional OptionRetention retention = 17; + + // This indicates the types of entities that the field may apply to when used + // as an option. If it is unset, then the field may be freely used as an + // option on any kind of entity. Note: as of January 2023, support for this is + // in progress and does not yet have an effect (b/264593489). + enum OptionTargetType { + TARGET_TYPE_UNKNOWN = 0; + TARGET_TYPE_FILE = 1; + TARGET_TYPE_EXTENSION_RANGE = 2; + TARGET_TYPE_MESSAGE = 3; + TARGET_TYPE_FIELD = 4; + TARGET_TYPE_ONEOF = 5; + TARGET_TYPE_ENUM = 6; + TARGET_TYPE_ENUM_ENTRY = 7; + TARGET_TYPE_SERVICE = 8; + TARGET_TYPE_METHOD = 9; + } + + repeated OptionTargetType targets = 19; + + message EditionDefault { + optional Edition edition = 3; + optional string value = 2; // Textproto value. + } + repeated EditionDefault edition_defaults = 20; + + // Any features defined in the specific edition. + optional FeatureSet features = 21; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; + + reserved 4; // removed jtype + reserved 18; // reserve target, target_obsolete_do_not_use +} + +message OneofOptions { + // Any features defined in the specific edition. + optional FeatureSet features = 1; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [default = false]; + + reserved 5; // javanano_as_lite + + // Enable the legacy handling of JSON field name conflicts. This lowercases + // and strips underscored from the fields before comparison in proto3 only. + // The new behavior takes `json_name` into account and applies to proto2 as + // well. + // TODO Remove this legacy behavior once downstream teams have + // had time to migrate. + optional bool deprecated_legacy_json_field_conflicts = 6 [deprecated = true]; + + // Any features defined in the specific edition. + optional FeatureSet features = 7; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [default = false]; + + // Any features defined in the specific edition. + optional FeatureSet features = 2; + + // Indicate that fields annotated with this enum value should not be printed + // out when using debug formats, e.g. when the field contains sensitive + // credentials. + optional bool debug_redact = 3 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Any features defined in the specific edition. + optional FeatureSet features = 34; + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [default = false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [default = false]; + + // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + // or neither? HTTP based RPC implementation may choose GET verb for safe + // methods, and PUT verb for idempotent methods instead of the default POST. + enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0; + NO_SIDE_EFFECTS = 1; // implies idempotent + IDEMPOTENT = 2; // idempotent, but may have side effects + } + optional IdempotencyLevel idempotency_level = 34 + [default = IDEMPOTENCY_UNKNOWN]; + + // Any features defined in the specific edition. + optional FeatureSet features = 35; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Features + +// TODO Enums in C++ gencode (and potentially other languages) are +// not well scoped. This means that each of the feature enums below can clash +// with each other. The short names we've chosen maximize call-site +// readability, but leave us very open to this scenario. A future feature will +// be designed and implemented to handle this, hopefully before we ever hit a +// conflict here. +message FeatureSet { + enum FieldPresence { + FIELD_PRESENCE_UNKNOWN = 0; + EXPLICIT = 1; + IMPLICIT = 2; + LEGACY_REQUIRED = 3; + } + optional FieldPresence field_presence = 1 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPLICIT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "IMPLICIT" }, + edition_defaults = { edition: EDITION_2023, value: "EXPLICIT" } + ]; + + enum EnumType { + ENUM_TYPE_UNKNOWN = 0; + OPEN = 1; + CLOSED = 2; + } + optional EnumType enum_type = 2 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "CLOSED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "OPEN" } + ]; + + enum RepeatedFieldEncoding { + REPEATED_FIELD_ENCODING_UNKNOWN = 0; + PACKED = 1; + EXPANDED = 2; + } + optional RepeatedFieldEncoding repeated_field_encoding = 3 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "EXPANDED" }, + edition_defaults = { edition: EDITION_PROTO3, value: "PACKED" } + ]; + + enum Utf8Validation { + UTF8_VALIDATION_UNKNOWN = 0; + NONE = 1; + VERIFY = 2; + } + optional Utf8Validation utf8_validation = 4 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "NONE" }, + edition_defaults = { edition: EDITION_PROTO3, value: "VERIFY" } + ]; + + enum MessageEncoding { + MESSAGE_ENCODING_UNKNOWN = 0; + LENGTH_PREFIXED = 1; + DELIMITED = 2; + } + optional MessageEncoding message_encoding = 5 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_FIELD, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LENGTH_PREFIXED" } + ]; + + enum JsonFormat { + JSON_FORMAT_UNKNOWN = 0; + ALLOW = 1; + LEGACY_BEST_EFFORT = 2; + } + optional JsonFormat json_format = 6 [ + retention = RETENTION_RUNTIME, + targets = TARGET_TYPE_MESSAGE, + targets = TARGET_TYPE_ENUM, + targets = TARGET_TYPE_FILE, + edition_defaults = { edition: EDITION_PROTO2, value: "LEGACY_BEST_EFFORT" }, + edition_defaults = { edition: EDITION_PROTO3, value: "ALLOW" } + ]; + + reserved 999; + + extensions 1000; // for Protobuf C++ + extensions 1001; // for Protobuf Java + + extensions 9995 to 9999; // For internal testing +} + +// A compiled specification for the defaults of a set of features. These +// messages are generated from FeatureSet extensions and can be used to seed +// feature resolution. The resolution with this object becomes a simple search +// for the closest matching edition, followed by proto merges. +message FeatureSetDefaults { + // A map from every known edition with a unique set of defaults to its + // defaults. Not all editions may be contained here. For a given edition, + // the defaults at the closest matching edition ordered at or before it should + // be used. This field must be in strict ascending order by edition. + message FeatureSetEditionDefault { + optional Edition edition = 3; + optional FeatureSet features = 2; + } + repeated FeatureSetEditionDefault defaults = 1; + + // The minimum supported edition (inclusive) when this was constructed. + // Editions before this will not have defaults. + optional Edition minimum_edition = 4; + + // The maximum known edition (inclusive) when this was constructed. Editions + // after this will not have reliable defaults. + optional Edition maximum_edition = 5; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition occurs. + // For example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed = true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed = true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to moo. + // // + // // Another line attached to moo. + // optional double moo = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to moo or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +message GeneratedCodeInfo { + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + repeated Annotation annotation = 1; + message Annotation { + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + repeated int32 path = 1 [packed = true]; + + // Identifies the filesystem path to the original source .proto. + optional string source_file = 2; + + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + optional int32 begin = 3; + + // Identifies the ending offset in bytes in the generated code that + // relates to the identified object. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + optional int32 end = 4; + + // Represents the identified object's effect on the element in the original + // .proto file. + enum Semantic { + // There is no effect or the effect is indescribable. + NONE = 0; + // The element is set or otherwise mutated. + SET = 1; + // An alias to the element is returned. + ALIAS = 2; + } + optional Semantic semantic = 5; + } +} diff --git a/protoc-gen-rpc-swagger/example/idl/hello.proto b/protoc-gen-rpc-swagger/example/idl/hello.proto new file mode 100644 index 0000000..64cb9b5 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/hello.proto @@ -0,0 +1,137 @@ +syntax = "proto3"; + +package hello; + +option go_package = "/example"; + +import "api.proto"; +import "openapi/annotations.proto"; + +option (openapi.document) = { + info: { + title: "example swagger doc"; + version: "Version from annotation"; + } +}; + +message FormReq { + option (openapi.schema) = { + title: "Hello - request"; + description: "Hello - request"; + required: [ + "form1" + ]; + }; + + string FormValue = 1 [ + (openapi.property) = { + title: "this is an override field schema title"; + max_length: 255; + } + ]; + + //内嵌message描述 + message InnerForm { + string InnerFormValue = 1; + } + + InnerForm FormValue1 = 2; +} + +message QueryReq { + map strings_map = 7; + repeated string items = 6; + //QueryValue描述 + string QueryValue = 1 [ + (openapi.parameter) = { + required: true; + }, + (openapi.property) = { + title: "Name"; + description: "Name"; + type: "string"; + min_length: 1; + max_length: 50; + } + ]; +} + +message PathReq { + //field: path描述 + string PathValue = 1; +} + +message BodyReq { + //field: body描述 + string BodyValue = 1; + //field: query描述 + string QueryValue = 2; + //field: body1描述 + string Body1Value = 3; +} + +message HelloReq { + + string Name = 1[ + (openapi.property) = { + title: "Name"; + description: "Name"; + type: "string"; + min_length: 1; + max_length: 50; + } + ]; +} + +// HelloResp描述 +message HelloResp { + option (openapi.schema) = { + title: "Hello - response"; + description: "Hello - response"; + required: [ + "RespBody" + ]; + }; + + //RespBody描述 + string RespBody = 1[ + (openapi.property) = { + title: "response content"; + description: "response content"; + type: "string"; + min_length: 1; + max_length: 80; + } + ]; + + string token = 2[ + (openapi.property) = { + title: "token"; + description: "token"; + type: "string"; + } + ]; +} + +//HelloService1描述 +service HelloService1 { + option (api.base_domain) = "http://127.0.0.1:8080"; + rpc QueryMethod1(QueryReq) returns (HelloResp) {} + + rpc FormMethod(FormReq) returns (HelloResp) {} + + rpc PathMethod(PathReq) returns (HelloResp) {} + + rpc BodyMethod(BodyReq) returns (HelloResp) {} + +} + +service HelloService2 { + rpc QueryMethod2(QueryReq) returns (HelloResp) { + option (api.baseurl) = "http://127.0.0.1:8080"; + option(openapi.operation) = { + summary: "Hello - Get"; + description: "Hello - Get"; + }; + } +} \ No newline at end of file diff --git a/protoc-gen-rpc-swagger/example/idl/openapi/annotations.proto b/protoc-gen-rpc-swagger/example/idl/openapi/annotations.proto new file mode 100644 index 0000000..c49cfe0 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/openapi/annotations.proto @@ -0,0 +1,80 @@ +// Copyright 2022 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +syntax = "proto3"; + +package openapi; + +import "openapi/openapi.proto"; +import "google/protobuf/descriptor.proto"; + +// This option lets the proto compiler generate Java code inside the package +// name (see below) instead of inside an outer class. It creates a simpler +// developer experience by reducing one-level of name nesting and be +// consistent with most programming languages that don't support outer classes. +option java_multiple_files = true; + +// The Java outer classname should be the filename in UpperCamelCase. This +// class is only used to hold proto descriptor, so developers don't need to +// work with it directly. +option java_outer_classname = "AnnotationsProto"; + +// The Java package name must be proto package name with proper prefix. +option java_package = "org.openapi_v3"; + +// A reasonable prefix for the Objective-C symbols generated from the package. +// It should at a minimum be 3 characters long, all uppercase, and convention +// is to use an abbreviation of the package name. Something short, but +// hopefully unique enough to not conflict with things that may come along in +// the future. 'GPB' is reserved for the protocol buffer implementation itself. +option objc_class_prefix = "OAS"; + +// The Go package name. +option go_package = "/openapi"; + +extend google.protobuf.FileOptions { + Document document = 1143; +} + +extend google.protobuf.MethodOptions { + Operation operation = 1143; +} + +extend google.protobuf.MessageOptions { + Schema schema = 1143; +} + +extend google.protobuf.FieldOptions { + Parameter parameter = 1144; +} + +extend google.protobuf.FieldOptions { + Schema property = 1143; +} \ No newline at end of file diff --git a/protoc-gen-rpc-swagger/example/idl/openapi/openapi.proto b/protoc-gen-rpc-swagger/example/idl/openapi/openapi.proto new file mode 100644 index 0000000..169fb8f --- /dev/null +++ b/protoc-gen-rpc-swagger/example/idl/openapi/openapi.proto @@ -0,0 +1,654 @@ +// Copyright 2020 Google LLC. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// THIS FILE IS AUTOMATICALLY GENERATED. + +syntax = "proto3"; + +package openapi; + +// The Go package name. +option go_package = "/openapi"; + +message AdditionalPropertiesItem { + oneof oneof { + SchemaOrReference schema_or_reference = 1; + bool boolean = 2; + } +} + +message _Any { + string type_url = 1; + bytes value = 2; +} + +message Any { + _Any value = 1; + string yaml = 2; +} + +message AnyOrExpression { + oneof oneof { + Any any = 1; + Expression expression = 2; + } +} + +// A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. +message Callback { + repeated NamedPathItem path = 1; + repeated NamedAny specification_extension = 2; +} + +message CallbackOrReference { + oneof oneof { + Callback callback = 1; + Reference reference = 2; + } +} + +message CallbacksOrReferences { + repeated NamedCallbackOrReference additional_properties = 1; +} + +// Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. +message Components { + SchemasOrReferences schemas = 1; + ResponsesOrReferences responses = 2; + ParametersOrReferences parameters = 3; + ExamplesOrReferences examples = 4; + RequestBodiesOrReferences request_bodies = 5; + HeadersOrReferences headers = 6; + SecuritySchemesOrReferences security_schemes = 7; + LinksOrReferences links = 8; + CallbacksOrReferences callbacks = 9; + repeated NamedAny specification_extension = 10; +} + +// Contact information for the exposed API. +message Contact { + string name = 1; + string url = 2; + string email = 3; + repeated NamedAny specification_extension = 4; +} + +message DefaultType { + oneof oneof { + double number = 1; + bool boolean = 2; + string string = 3; + } +} + +// When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. When using the discriminator, _inline_ schemas will not be considered. +message Discriminator { + string property_name = 1; + Strings mapping = 2; + repeated NamedAny specification_extension = 3; +} + +message Document { + string openapi = 1; + Info info = 2; + repeated Server servers = 3; + Paths paths = 4; + Components components = 5; + repeated SecurityRequirement security = 6; + repeated Tag tags = 7; + ExternalDocs external_docs = 8; + repeated NamedAny specification_extension = 9; +} + +// A single encoding definition applied to a single schema property. +message Encoding { + string content_type = 1; + HeadersOrReferences headers = 2; + string style = 3; + bool explode = 4; + bool allow_reserved = 5; + repeated NamedAny specification_extension = 6; +} + +message Encodings { + repeated NamedEncoding additional_properties = 1; +} + +message Example { + string summary = 1; + string description = 2; + Any value = 3; + string external_value = 4; + repeated NamedAny specification_extension = 5; +} + +message ExampleOrReference { + oneof oneof { + Example example = 1; + Reference reference = 2; + } +} + +message ExamplesOrReferences { + repeated NamedExampleOrReference additional_properties = 1; +} + +message Expression { + repeated NamedAny additional_properties = 1; +} + +// Allows referencing an external resource for extended documentation. +message ExternalDocs { + string description = 1; + string url = 2; + repeated NamedAny specification_extension = 3; +} + +// The Header Object follows the structure of the Parameter Object with the following changes: 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. 1. `in` MUST NOT be specified, it is implicitly in `header`. 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`). +message Header { + string description = 1; + bool required = 2; + bool deprecated = 3; + bool allow_empty_value = 4; + string style = 5; + bool explode = 6; + bool allow_reserved = 7; + SchemaOrReference schema = 8; + Any example = 9; + ExamplesOrReferences examples = 10; + MediaTypes content = 11; + repeated NamedAny specification_extension = 12; +} + +message HeaderOrReference { + oneof oneof { + Header header = 1; + Reference reference = 2; + } +} + +message HeadersOrReferences { + repeated NamedHeaderOrReference additional_properties = 1; +} + +// The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. +message Info { + string title = 1; + string description = 2; + string terms_of_service = 3; + Contact contact = 4; + License license = 5; + string version = 6; + repeated NamedAny specification_extension = 7; + string summary = 8; +} + +message ItemsItem { + repeated SchemaOrReference schema_or_reference = 1; +} + +// License information for the exposed API. +message License { + string name = 1; + string url = 2; + repeated NamedAny specification_extension = 3; +} + +// The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation. +message Link { + string operation_ref = 1; + string operation_id = 2; + AnyOrExpression parameters = 3; + AnyOrExpression request_body = 4; + string description = 5; + Server server = 6; + repeated NamedAny specification_extension = 7; +} + +message LinkOrReference { + oneof oneof { + Link link = 1; + Reference reference = 2; + } +} + +message LinksOrReferences { + repeated NamedLinkOrReference additional_properties = 1; +} + +// Each Media Type Object provides schema and examples for the media type identified by its key. +message MediaType { + SchemaOrReference schema = 1; + Any example = 2; + ExamplesOrReferences examples = 3; + Encodings encoding = 4; + repeated NamedAny specification_extension = 5; +} + +message MediaTypes { + repeated NamedMediaType additional_properties = 1; +} + +// Automatically-generated message used to represent maps of Any as ordered (name,value) pairs. +message NamedAny { + // Map key + string name = 1; + // Mapped value + Any value = 2; +} + +// Automatically-generated message used to represent maps of CallbackOrReference as ordered (name,value) pairs. +message NamedCallbackOrReference { + // Map key + string name = 1; + // Mapped value + CallbackOrReference value = 2; +} + +// Automatically-generated message used to represent maps of Encoding as ordered (name,value) pairs. +message NamedEncoding { + // Map key + string name = 1; + // Mapped value + Encoding value = 2; +} + +// Automatically-generated message used to represent maps of ExampleOrReference as ordered (name,value) pairs. +message NamedExampleOrReference { + // Map key + string name = 1; + // Mapped value + ExampleOrReference value = 2; +} + +// Automatically-generated message used to represent maps of HeaderOrReference as ordered (name,value) pairs. +message NamedHeaderOrReference { + // Map key + string name = 1; + // Mapped value + HeaderOrReference value = 2; +} + +// Automatically-generated message used to represent maps of LinkOrReference as ordered (name,value) pairs. +message NamedLinkOrReference { + // Map key + string name = 1; + // Mapped value + LinkOrReference value = 2; +} + +// Automatically-generated message used to represent maps of MediaType as ordered (name,value) pairs. +message NamedMediaType { + // Map key + string name = 1; + // Mapped value + MediaType value = 2; +} + +// Automatically-generated message used to represent maps of ParameterOrReference as ordered (name,value) pairs. +message NamedParameterOrReference { + // Map key + string name = 1; + // Mapped value + ParameterOrReference value = 2; +} + +// Automatically-generated message used to represent maps of PathItem as ordered (name,value) pairs. +message NamedPathItem { + // Map key + string name = 1; + // Mapped value + PathItem value = 2; +} + +// Automatically-generated message used to represent maps of RequestBodyOrReference as ordered (name,value) pairs. +message NamedRequestBodyOrReference { + // Map key + string name = 1; + // Mapped value + RequestBodyOrReference value = 2; +} + +// Automatically-generated message used to represent maps of ResponseOrReference as ordered (name,value) pairs. +message NamedResponseOrReference { + // Map key + string name = 1; + // Mapped value + ResponseOrReference value = 2; +} + +// Automatically-generated message used to represent maps of SchemaOrReference as ordered (name,value) pairs. +message NamedSchemaOrReference { + // Map key + string name = 1; + // Mapped value + SchemaOrReference value = 2; +} + +// Automatically-generated message used to represent maps of SecuritySchemeOrReference as ordered (name,value) pairs. +message NamedSecuritySchemeOrReference { + // Map key + string name = 1; + // Mapped value + SecuritySchemeOrReference value = 2; +} + +// Automatically-generated message used to represent maps of ServerVariable as ordered (name,value) pairs. +message NamedServerVariable { + // Map key + string name = 1; + // Mapped value + ServerVariable value = 2; +} + +// Automatically-generated message used to represent maps of string as ordered (name,value) pairs. +message NamedString { + // Map key + string name = 1; + // Mapped value + string value = 2; +} + +// Automatically-generated message used to represent maps of StringArray as ordered (name,value) pairs. +message NamedStringArray { + // Map key + string name = 1; + // Mapped value + StringArray value = 2; +} + +// Configuration details for a supported OAuth Flow +message OauthFlow { + string authorization_url = 1; + string token_url = 2; + string refresh_url = 3; + Strings scopes = 4; + repeated NamedAny specification_extension = 5; +} + +// Allows configuration of the supported OAuth Flows. +message OauthFlows { + OauthFlow implicit = 1; + OauthFlow password = 2; + OauthFlow client_credentials = 3; + OauthFlow authorization_code = 4; + repeated NamedAny specification_extension = 5; +} + +message Object { + repeated NamedAny additional_properties = 1; +} + +// Describes a single API operation on a path. +message Operation { + repeated string tags = 1; + string summary = 2; + string description = 3; + ExternalDocs external_docs = 4; + string operation_id = 5; + repeated ParameterOrReference parameters = 6; + RequestBodyOrReference request_body = 7; + Responses responses = 8; + CallbacksOrReferences callbacks = 9; + bool deprecated = 10; + repeated SecurityRequirement security = 11; + repeated Server servers = 12; + repeated NamedAny specification_extension = 13; +} + +// Describes a single operation parameter. A unique parameter is defined by a combination of a name and location. +message Parameter { + string name = 1; + string in = 2; + string description = 3; + bool required = 4; + bool deprecated = 5; + bool allow_empty_value = 6; + string style = 7; + bool explode = 8; + bool allow_reserved = 9; + SchemaOrReference schema = 10; + Any example = 11; + ExamplesOrReferences examples = 12; + MediaTypes content = 13; + repeated NamedAny specification_extension = 14; +} + +message ParameterOrReference { + oneof oneof { + Parameter parameter = 1; + Reference reference = 2; + } +} + +message ParametersOrReferences { + repeated NamedParameterOrReference additional_properties = 1; +} + +// Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. +message PathItem { + string _ref = 1; + string summary = 2; + string description = 3; + Operation get = 4; + Operation put = 5; + Operation post = 6; + Operation delete = 7; + Operation options = 8; + Operation head = 9; + Operation patch = 10; + Operation trace = 11; + repeated Server servers = 12; + repeated ParameterOrReference parameters = 13; + repeated NamedAny specification_extension = 14; +} + +// Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the `Server Object` in order to construct the full URL. The Paths MAY be empty, due to ACL constraints. +message Paths { + repeated NamedPathItem path = 1; + repeated NamedAny specification_extension = 2; +} + +message Properties { + repeated NamedSchemaOrReference additional_properties = 1; +} + +// A simple object to allow referencing other components in the specification, internally and externally. The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules. For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. +message Reference { + string _ref = 1; + string summary = 2; + string description = 3; +} + +message RequestBodiesOrReferences { + repeated NamedRequestBodyOrReference additional_properties = 1; +} + +// Describes a single request body. +message RequestBody { + string description = 1; + MediaTypes content = 2; + bool required = 3; + repeated NamedAny specification_extension = 4; +} + +message RequestBodyOrReference { + oneof oneof { + RequestBody request_body = 1; + Reference reference = 2; + } +} + +// Describes a single response from an API Operation, including design-time, static `links` to operations based on the response. +message Response { + string description = 1; + HeadersOrReferences headers = 2; + MediaTypes content = 3; + LinksOrReferences links = 4; + repeated NamedAny specification_extension = 5; +} + +message ResponseOrReference { + oneof oneof { + Response response = 1; + Reference reference = 2; + } +} + +// A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call. +message Responses { + ResponseOrReference default = 1; + repeated NamedResponseOrReference response_or_reference = 2; + repeated NamedAny specification_extension = 3; +} + +message ResponsesOrReferences { + repeated NamedResponseOrReference additional_properties = 1; +} + +// The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema. +message Schema { + bool nullable = 1; + Discriminator discriminator = 2; + bool read_only = 3; + bool write_only = 4; + Xml xml = 5; + ExternalDocs external_docs = 6; + Any example = 7; + bool deprecated = 8; + string title = 9; + double multiple_of = 10; + double maximum = 11; + bool exclusive_maximum = 12; + double minimum = 13; + bool exclusive_minimum = 14; + int64 max_length = 15; + int64 min_length = 16; + string pattern = 17; + int64 max_items = 18; + int64 min_items = 19; + bool unique_items = 20; + int64 max_properties = 21; + int64 min_properties = 22; + repeated string required = 23; + repeated Any enum = 24; + string type = 25; + repeated SchemaOrReference all_of = 26; + repeated SchemaOrReference one_of = 27; + repeated SchemaOrReference any_of = 28; + Schema not = 29; + ItemsItem items = 30; + Properties properties = 31; + AdditionalPropertiesItem additional_properties = 32; + DefaultType default = 33; + string description = 34; + string format = 35; + repeated NamedAny specification_extension = 36; +} + +message SchemaOrReference { + oneof oneof { + Schema schema = 1; + Reference reference = 2; + } +} + +message SchemasOrReferences { + repeated NamedSchemaOrReference additional_properties = 1; +} + +// Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object. Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. +message SecurityRequirement { + repeated NamedStringArray additional_properties = 1; +} + +// Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect. Please note that currently (2019) the implicit flow is about to be deprecated OAuth 2.0 Security Best Current Practice. Recommended for most use case is Authorization Code Grant flow with PKCE. +message SecurityScheme { + string type = 1; + string description = 2; + string name = 3; + string in = 4; + string scheme = 5; + string bearer_format = 6; + OauthFlows flows = 7; + string open_id_connect_url = 8; + repeated NamedAny specification_extension = 9; +} + +message SecuritySchemeOrReference { + oneof oneof { + SecurityScheme security_scheme = 1; + Reference reference = 2; + } +} + +message SecuritySchemesOrReferences { + repeated NamedSecuritySchemeOrReference additional_properties = 1; +} + +// An object representing a Server. +message Server { + string url = 1; + string description = 2; + ServerVariables variables = 3; + repeated NamedAny specification_extension = 4; +} + +// An object representing a Server Variable for server URL template substitution. +message ServerVariable { + repeated string enum = 1; + string default = 2; + string description = 3; + repeated NamedAny specification_extension = 4; +} + +message ServerVariables { + repeated NamedServerVariable additional_properties = 1; +} + +// Any property starting with x- is valid. +message SpecificationExtension { + oneof oneof { + double number = 1; + bool boolean = 2; + string string = 3; + } +} + +message StringArray { + repeated string value = 1; +} + +message Strings { + repeated NamedString additional_properties = 1; +} + +// Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. +message Tag { + string name = 1; + string description = 2; + ExternalDocs external_docs = 3; + repeated NamedAny specification_extension = 4; +} + +// A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior. +message Xml { + string name = 1; + string namespace = 2; + string prefix = 3; + bool attribute = 4; + bool wrapped = 5; + repeated NamedAny specification_extension = 6; +} + diff --git a/protoc-gen-rpc-swagger/example/swagger/openapi.yaml b/protoc-gen-rpc-swagger/example/swagger/openapi.yaml new file mode 100644 index 0000000..266d680 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/swagger/openapi.yaml @@ -0,0 +1,202 @@ +# Generated with protoc-gen-rpc-swagger +# https://github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger + +openapi: 3.0.3 +info: + title: example swagger doc + version: Version from annotation +servers: + - url: http://127.0.0.1:8080 +paths: + /BodyMethod: + post: + tags: + - HelloService1 + operationId: HelloService1_BodyMethod + parameters: + - name: ttheader + in: query + description: metainfo for request + schema: + type: object + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/BodyReq' + responses: + "200": + description: HelloResp描述 + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResp' + /FormMethod: + post: + tags: + - HelloService1 + operationId: HelloService1_FormMethod + parameters: + - name: ttheader + in: query + description: metainfo for request + schema: + type: object + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FormReq' + responses: + "200": + description: HelloResp描述 + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResp' + /PathMethod: + post: + tags: + - HelloService1 + operationId: HelloService1_PathMethod + parameters: + - name: ttheader + in: query + description: metainfo for request + schema: + type: object + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PathReq' + responses: + "200": + description: HelloResp描述 + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResp' + /QueryMethod1: + post: + tags: + - HelloService1 + operationId: HelloService1_QueryMethod1 + parameters: + - name: ttheader + in: query + description: metainfo for request + schema: + type: object + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/QueryReq' + responses: + "200": + description: HelloResp描述 + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResp' + /QueryMethod2: + post: + tags: + - HelloService2 + summary: Hello - Get + description: Hello - Get + operationId: HelloService2_QueryMethod2 + parameters: + - name: ttheader + in: query + description: metainfo for request + schema: + type: object + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/QueryReq' + responses: + "200": + description: HelloResp描述 + content: + application/json: + schema: + $ref: '#/components/schemas/HelloResp' +components: + schemas: + BodyReq: + type: object + properties: + BodyValue: + type: string + description: 'field: body描述' + QueryValue: + type: string + description: 'field: query描述' + Body1Value: + type: string + description: 'field: body1描述' + FormReq: + title: Hello - request + type: object + properties: + FormValue: + title: this is an override field schema title + maxLength: 255 + type: string + FormValue1: + $ref: '#/components/schemas/FormReq_InnerForm' + description: Hello - request + FormReq_InnerForm: + type: object + properties: + InnerFormValue: + type: string + description: 内嵌message描述 + HelloResp: + title: Hello - response + required: + - RespBody + type: object + properties: + RespBody: + title: response content + maxLength: 80 + minLength: 1 + type: string + description: response content + token: + title: token + type: string + description: token + description: Hello - response + PathReq: + type: object + properties: + PathValue: + type: string + description: 'field: path描述' + QueryReq: + type: object + properties: + stringsMap: + type: object + additionalProperties: + type: string + items: + type: array + items: + type: string + QueryValue: + title: Name + maxLength: 50 + minLength: 1 + type: string + description: Name +tags: + - name: HelloService1 + description: HelloService1描述 + - name: HelloService2 diff --git a/protoc-gen-rpc-swagger/example/swagger/swagger.go b/protoc-gen-rpc-swagger/example/swagger/swagger.go new file mode 100644 index 0000000..0742fa0 --- /dev/null +++ b/protoc-gen-rpc-swagger/example/swagger/swagger.go @@ -0,0 +1,289 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Code generated by protoc-gen-rpc-swagger. +package swagger + +import ( + "context" + _ "embed" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + + "github.com/bytedance/gopkg/cloud/metainfo" + "github.com/cloudwego/dynamicgo/proto" + "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego/hertz/pkg/app/server" + "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/cloudwego/hertz/pkg/network" + "github.com/cloudwego/hertz/pkg/route" + "github.com/cloudwego/kitex/client" + "github.com/cloudwego/kitex/client/genericclient" + "github.com/cloudwego/kitex/pkg/endpoint" + "github.com/cloudwego/kitex/pkg/generic" + "github.com/cloudwego/kitex/pkg/klog" + "github.com/cloudwego/kitex/pkg/remote" + "github.com/cloudwego/kitex/pkg/remote/trans/detection" + "github.com/cloudwego/kitex/pkg/remote/trans/netpoll" + "github.com/cloudwego/kitex/pkg/remote/trans/nphttp2" + "github.com/cloudwego/kitex/pkg/transmeta" + "github.com/cloudwego/kitex/transport" + "github.com/hertz-contrib/cors" + "github.com/hertz-contrib/swagger" + swaggerFiles "github.com/swaggo/files" +) + +var ( + //go:embed openapi.yaml + openapiYAML []byte + hertzEngine *route.Engine + httpReg = regexp.MustCompile("^(?:GET |POST|PUT|DELE|HEAD|OPTI|CONN|TRAC|PATC)$") +) + +const ( + kitexAddr = "127.0.0.1:8888" + idlFile = "hello.proto" +) + +type MixTransHandlerFactory struct { + OriginFactory remote.ServerTransHandlerFactory +} + +type transHandler struct { + remote.ServerTransHandler +} + +func (t *transHandler) SetInvokeHandleFunc(inkHdlFunc endpoint.Endpoint) { + t.ServerTransHandler.(remote.InvokeHandleFuncSetter).SetInvokeHandleFunc(inkHdlFunc) +} + +func (m MixTransHandlerFactory) NewTransHandler(opt *remote.ServerOption) (remote.ServerTransHandler, error) { + if hertzEngine == nil { + StartServer() + } + + var kitexOrigin remote.ServerTransHandler + var err error + + if m.OriginFactory != nil { + kitexOrigin, err = m.OriginFactory.NewTransHandler(opt) + } else { + kitexOrigin, err = detection.NewSvrTransHandlerFactory(netpoll.NewSvrTransHandlerFactory(), nphttp2.NewSvrTransHandlerFactory()).NewTransHandler(opt) + } + if err != nil { + return nil, err + } + return &transHandler{ServerTransHandler: kitexOrigin}, nil +} + +func (t *transHandler) OnRead(ctx context.Context, conn net.Conn) error { + c, ok := conn.(network.Conn) + if ok { + pre, _ := c.Peek(4) + if httpReg.Match(pre) { + klog.Info("using Hertz to process request") + err := hertzEngine.Serve(ctx, c) + if err != nil { + err = errors.New(fmt.Sprintf("HERTZ: %s", err.Error())) + } + return err + } + } + + return t.ServerTransHandler.OnRead(ctx, conn) +} + +func StartServer() { + h := server.Default() + h.Use(cors.Default()) + + cli := initializeGenericClient() + setupSwaggerRoutes(h) + setupProxyRoutes(h, cli) + + hlog.Info("Swagger UI is available at: http://" + kitexAddr + "/swagger/index.html") + err := h.Engine.Init() + if err != nil { + panic(err) + } + + hertzEngine = h.Engine +} + +func findPbFile(fileName string) (string, error) { + workingDir, err := os.Getwd() + if err != nil { + return "", err + } + + foundPath := "" + relativePath := fileName + + err = filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if !info.IsDir() { + relative, err := filepath.Rel(workingDir, path) + if err != nil { + return err + } + + if relative == relativePath { + foundPath = path + return filepath.SkipDir + } + } + return nil + }) + + if err == nil && foundPath != "" { + return foundPath, nil + } + + parentDir := filepath.Dir(workingDir) + for parentDir != "/" && parentDir != "." && parentDir != workingDir { + filePath := filepath.Join(parentDir, fileName) + if _, err := os.Stat(filePath); err == nil { + return filePath, nil + } + workingDir = parentDir + parentDir = filepath.Dir(parentDir) + } + + return "", errors.New("proto file not found: " + fileName) +} + +func initializeGenericClient() genericclient.Client { + pbFile, err := findPbFile(idlFile) + if err != nil { + hlog.Fatal("Failed to locate Proto file:", err) + } + + dOpts := proto.Options{} + p, err := generic.NewPbFileProviderWithDynamicGo(pbFile, context.Background(), dOpts) + if err != nil { + hlog.Fatal("Failed to create PbFileProvider:", err) + } + + g, err := generic.JSONPbGeneric(p) + if err != nil { + hlog.Fatal("Failed to create JsonPbGeneric:", err) + } + var opts []client.Option + opts = append(opts, client.WithTransportProtocol(transport.TTHeader)) + opts = append(opts, client.WithMetaHandler(transmeta.ClientTTHeaderHandler)) + opts = append(opts, client.WithHostPorts(kitexAddr)) + cli, err := genericclient.NewClient("swagger", g, opts...) + if err != nil { + hlog.Fatal("Failed to create generic client:", err) + } + + return cli +} + +func setupSwaggerRoutes(h *server.Hertz) { + h.GET("swagger/*any", swagger.WrapHandler(swaggerFiles.Handler, swagger.URL("/openapi.yaml"))) + + h.GET("/openapi.yaml", func(c context.Context, ctx *app.RequestContext) { + ctx.Header("Content-Type", "application/x-yaml") + ctx.Write(openapiYAML) + }) +} + +func setupProxyRoutes(h *server.Hertz, cli genericclient.Client) { + h.Any("/*ServiceMethod", func(c context.Context, ctx *app.RequestContext) { + serviceMethod := ctx.Param("ServiceMethod") + if serviceMethod == "" { + handleError(ctx, "ServiceMethod not provided", http.StatusBadRequest) + return + } + + bodyBytes := ctx.Request.Body() + + queryMap := formatQueryParams(ctx) + + for k, v := range queryMap { + if strings.HasPrefix(k, "p_") { + c = metainfo.WithPersistentValue(c, k, v) + } else { + c = metainfo.WithValue(c, k, v) + } + } + + c = metainfo.WithBackwardValues(c) + + jReq := string(bodyBytes) + + jRsp, err := cli.GenericCall(c, serviceMethod, jReq) + if err != nil { + hlog.Errorf("GenericCall error: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": err.Error(), + }) + return + } + + result := make(map[string]interface{}) + if err := json.Unmarshal([]byte(jRsp.(string)), &result); err != nil { + hlog.Errorf("Failed to unmarshal response body: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": "Failed to unmarshal response body", + }) + return + } + + m := metainfo.RecvAllBackwardValues(c) + + for key, value := range m { + result[key] = value + } + + respBody, err := json.Marshal(result) + if err != nil { + hlog.Errorf("Failed to marshal response body: %v", err) + ctx.JSON(500, map[string]interface{}{ + "error": "Failed to marshal response body", + }) + return + } + + ctx.Data(http.StatusOK, "application/json", respBody) + }) +} + +func formatQueryParams(ctx *app.RequestContext) map[string]string { + QueryParams := make(map[string]string) + ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) { + QueryParams[string(key)] = string(value) + }) + return QueryParams +} + +func handleError(ctx *app.RequestContext, errMsg string, statusCode int) { + hlog.Errorf("Error: %s", errMsg) + ctx.JSON(statusCode, map[string]interface{}{ + "error": errMsg, + }) +} diff --git a/protoc-gen-rpc-swagger/generator/openapi_gen.go b/protoc-gen-rpc-swagger/generator/openapi_gen.go new file mode 100644 index 0000000..c223351 --- /dev/null +++ b/protoc-gen-rpc-swagger/generator/openapi_gen.go @@ -0,0 +1,678 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright 2020 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file may have been modified by CloudWeGo authors. All CloudWeGo + * Modifications are Copyright 2024 CloudWeGo Authors. + */ + +package generator + +import ( + "fmt" + "regexp" + "sort" + "strings" + + "github.com/cloudwego/hertz/cmd/hz/util/logs" + "github.com/hertz-contrib/swagger-generate/common/consts" + common "github.com/hertz-contrib/swagger-generate/common/utils" + "github.com/hertz-contrib/swagger-generate/idl/protobuf/api" + "github.com/hertz-contrib/swagger-generate/idl/protobuf/openapi" + wk "github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger/generator/wellknown" + "google.golang.org/genproto/googleapis/api/annotations" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/proto" + any_pb "google.golang.org/protobuf/types/known/anypb" +) + +type Configuration struct { + Version *string + Title *string + Description *string + Naming *string + FQSchemaNaming *bool + EnumType *string + OutputMode *string +} + +// In order to dynamically add google.rpc.Status responses we need +// to know the message descriptors for google.rpc.Status as well +// as google.protobuf.Any. +var ( + anyProtoDesc = (&any_pb.Any{}).ProtoReflect().Descriptor() +) + +// OpenAPIGenerator holds internal state needed to generate an OpenAPIv3 document for a transcoded Protocol Buffer service. +type OpenAPIGenerator struct { + conf Configuration + plugin *protogen.Plugin + inputFiles []*protogen.File + reflect *OpenAPIReflector + generatedSchemas []string // Names of schemas that have already been generated. + linterRulePattern *regexp.Regexp +} + +// NewOpenAPIGenerator creates a new generator for a protoc plugin invocation. +func NewOpenAPIGenerator(plugin *protogen.Plugin, conf Configuration, inputFiles []*protogen.File) *OpenAPIGenerator { + return &OpenAPIGenerator{ + conf: conf, + plugin: plugin, + inputFiles: inputFiles, + reflect: NewOpenAPIReflector(conf), + generatedSchemas: make([]string, 0), + linterRulePattern: regexp.MustCompile(`\(-- .* --\)`), + } +} + +// Run runs the generator. +func (g *OpenAPIGenerator) Run(outputFile *protogen.GeneratedFile) error { + d := g.buildDocument() + bytes, err := d.YAMLValue("Generated with " + consts.PluginNameProtocRpcSwagger + "\n" + consts.InfoURL + consts.PluginNameProtocRpcSwagger) + if err != nil { + return fmt.Errorf("failed to marshal yaml: %s", err.Error()) + } + if _, err = outputFile.Write(bytes); err != nil { + return fmt.Errorf("failed to write yaml: %s", err.Error()) + } + return nil +} + +// buildDocument builds an OpenAPIv3 document for a plugin request. +func (g *OpenAPIGenerator) buildDocument() *openapi.Document { + d := &openapi.Document{} + + d.Openapi = consts.OpenAPIVersion + d.Info = &openapi.Info{ + Version: *g.conf.Version, + Title: *g.conf.Title, + Description: *g.conf.Description, + } + + d.Paths = &openapi.Paths{} + d.Components = &openapi.Components{ + Schemas: &openapi.SchemasOrReferences{ + AdditionalProperties: []*openapi.NamedSchemaOrReference{}, + }, + } + + // Go through the files and add the services to the documents, keeping + // track of which schemas are referenced in the response so we can + // add them later. + for _, file := range g.inputFiles { + if file.Generate { + // Merge any `Document` annotations with the current + extDocument := proto.GetExtension(file.Desc.Options(), openapi.E_Document) + if extDocument != nil { + if doc, ok := extDocument.(*openapi.Document); ok { + proto.Merge(d, doc) + } else { + logs.Errorf("unexpected type for Document: %T", extDocument) + } + } + g.addPathsToDocument(d, file.Services) + } + } + + // While we have required schemas left to generate, go through the files again + // looking for the related message and adding them to the document if required. + for len(g.reflect.requiredSchemas) > 0 { + count := len(g.reflect.requiredSchemas) + for _, file := range g.plugin.Files { + g.addSchemasForMessagesToDocument(d, file.Messages) + } + g.reflect.requiredSchemas = g.reflect.requiredSchemas[count:len(g.reflect.requiredSchemas)] + } + + // If there is only 1 service, then use it's title for the + // document, if the document is missing it. + if len(d.Tags) == 1 { + if d.Info.Title == "" && d.Tags[0].Name != "" { + d.Info.Title = d.Tags[0].Name + " API" + } + if d.Info.Description == "" { + d.Info.Description = d.Tags[0].Description + } + d.Tags[0].Description = "" + } + + var allServers []string + + // If paths methods has servers, but they're all the same, then move servers to path level + for _, path := range d.Paths.Path { + var servers []string + if path.Value.Post != nil && len(path.Value.Post.Servers) == 1 { + servers = common.AppendUnique(servers, path.Value.Post.Servers[0].Url) + allServers = common.AppendUnique(allServers, path.Value.Post.Servers[0].Url) + } + + if len(servers) == 1 { + path.Value.Servers = []*openapi.Server{{Url: servers[0]}} + if path.Value.Post != nil { + path.Value.Post.Servers = nil + } + } + } + + // Set all servers on API level + if len(allServers) > 0 { + d.Servers = []*openapi.Server{} + for _, server := range allServers { + d.Servers = append(d.Servers, &openapi.Server{Url: server}) + } + } + + // If there is only 1 server, we can safely remove all path level servers + if len(allServers) == 1 { + for _, path := range d.Paths.Path { + path.Value.Servers = nil + } + } + + // If there are no servers, add a default one + if len(allServers) == 0 { + d.Servers = []*openapi.Server{ + {Url: consts.DefaultServerURL}, + } + } + + // Sort the tags. + { + pairs := d.Tags + sort.Slice(pairs, func(i, j int) bool { + return pairs[i].Name < pairs[j].Name + }) + d.Tags = pairs + } + // Sort the paths. + { + pairs := d.Paths.Path + sort.Slice(pairs, func(i, j int) bool { + return pairs[i].Name < pairs[j].Name + }) + d.Paths.Path = pairs + } + // Sort the schemas. + { + pairs := d.Components.Schemas.AdditionalProperties + sort.Slice(pairs, func(i, j int) bool { + return pairs[i].Name < pairs[j].Name + }) + d.Components.Schemas.AdditionalProperties = pairs + } + return d +} + +// filterCommentString removes linter rules from comments. +func (g *OpenAPIGenerator) filterCommentString(c protogen.Comments) string { + comment := g.linterRulePattern.ReplaceAllString(string(c), "") + return strings.TrimSpace(comment) +} + +func (g *OpenAPIGenerator) getSchemaByOption(inputMessage *protogen.Message) *openapi.Schema { + // Build an array holding the fields of the message. + definitionProperties := &openapi.Properties{ + AdditionalProperties: make([]*openapi.NamedSchemaOrReference, 0), + } + // Merge any `Schema` annotations with the current + extSchema := proto.GetExtension(inputMessage.Desc.Options(), openapi.E_Schema) + var allRequired []string + if extSchema != nil { + if schema, ok := extSchema.(*openapi.Schema); ok && schema != nil { + if len(schema.Required) != 0 { + allRequired = schema.Required + } + } + } + var required []string + for _, field := range inputMessage.Fields { + extName := g.reflect.formatFieldName(field.Desc) + if common.Contains(allRequired, extName) { + required = append(required, extName) + } + // Get the field description from the comments. + description := g.filterCommentString(field.Comments.Leading) + // Check the field annotations to see if this is a readonly or writeonly field. + inputOnly := false + outputOnly := false + extension := proto.GetExtension(field.Desc.Options(), annotations.E_FieldBehavior) + if extension != nil { + switch v := extension.(type) { + case []annotations.FieldBehavior: + for _, vv := range v { + switch vv { + case annotations.FieldBehavior_OUTPUT_ONLY: + outputOnly = true + case annotations.FieldBehavior_INPUT_ONLY: + inputOnly = true + case annotations.FieldBehavior_REQUIRED: + required = append(required, g.reflect.formatFieldName(field.Desc)) + } + } + default: + logs.Errorf("unsupported extension type %T", extension) + } + } + + // The field is either described by a reference or a schema. + fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc) + if fieldSchema == nil { + continue + } + + // If this field has siblings and is a $ref now, create a new schema use `allOf` to wrap it + wrapperNeeded := inputOnly || outputOnly || description != "" + if wrapperNeeded { + if _, ok := fieldSchema.Oneof.(*openapi.SchemaOrReference_Reference); ok { + fieldSchema = &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: &openapi.Schema{ + AllOf: []*openapi.SchemaOrReference{fieldSchema}, + }}} + } + } + + if schema, ok := fieldSchema.Oneof.(*openapi.SchemaOrReference_Schema); ok { + schema.Schema.Description = description + schema.Schema.ReadOnly = outputOnly + schema.Schema.WriteOnly = inputOnly + + // Merge any `Property` annotations with the current + extProperty := proto.GetExtension(field.Desc.Options(), openapi.E_Property) + if extProperty != nil { + proto.Merge(schema.Schema, extProperty.(*openapi.Schema)) + } + } + + definitionProperties.AdditionalProperties = append( + definitionProperties.AdditionalProperties, + &openapi.NamedSchemaOrReference{ + Name: extName, + Value: fieldSchema, + }, + ) + } + + schema := &openapi.Schema{ + Type: consts.SchemaObjectType, + Properties: definitionProperties, + } + + // Merge any `Schema` annotations with the current + extSchema = proto.GetExtension(inputMessage.Desc.Options(), openapi.E_Schema) + if extSchema != nil { + proto.Merge(schema, extSchema.(*openapi.Schema)) + } + + schema.Required = required + return schema +} + +func (g *OpenAPIGenerator) buildOperation( + d *openapi.Document, + operationID string, + tagName string, + description string, + defaultHost string, + path string, + inputMessage *protogen.Message, + outputMessage *protogen.Message, +) (*openapi.Operation, string) { + // Parameters array to hold all parameter objects + var parameters []*openapi.ParameterOrReference + + fieldSchema := &openapi.SchemaOrReference{ + Oneof: &openapi.SchemaOrReference_Schema{ + Schema: &openapi.Schema{ + Type: consts.SchemaObjectType, + }, + }, + } + parameter := &openapi.Parameter{ + Name: consts.ParameterNameTTHeader, + In: consts.ParameterInQuery, + Description: consts.ParameterDescription, + Required: false, + Schema: fieldSchema, + } + + parameters = append(parameters, &openapi.ParameterOrReference{ + Oneof: &openapi.ParameterOrReference_Parameter{ + Parameter: parameter, + }, + }) + + var RequestBody *openapi.RequestBodyOrReference + var additionalProperties []*openapi.NamedMediaType + + bodySchema := g.getSchemaByOption(inputMessage) + + if len(bodySchema.Properties.AdditionalProperties) > 0 { + refSchema := &openapi.NamedSchemaOrReference{ + Name: g.reflect.formatMessageName(inputMessage.Desc), + Value: &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: bodySchema}}, + } + + ref := consts.ComponentSchemaPrefix + g.reflect.formatMessageName(inputMessage.Desc) + + g.addSchemaToDocument(d, refSchema) + + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ + Name: consts.ContentTypeJSON, + Value: &openapi.MediaType{ + Schema: &openapi.SchemaOrReference{ + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: ref}, + }, + }, + }, + }) + } + + if len(additionalProperties) > 0 { + RequestBody = &openapi.RequestBodyOrReference{ + Oneof: &openapi.RequestBodyOrReference_RequestBody{ + RequestBody: &openapi.RequestBody{ + Description: g.filterCommentString(inputMessage.Comments.Leading), + Content: &openapi.MediaTypes{ + AdditionalProperties: additionalProperties, + }, + }, + }, + } + } + + name, content := g.getResponseForMessage(d, outputMessage) + + desc := g.filterCommentString(outputMessage.Comments.Leading) + if desc == "" { + desc = consts.DefaultResponseDesc + } + + var contentOrEmpty *openapi.MediaTypes + if len(content.AdditionalProperties) != 0 { + contentOrEmpty = content + } + var responses *openapi.Responses + if contentOrEmpty != nil { + responses = &openapi.Responses{ + ResponseOrReference: []*openapi.NamedResponseOrReference{ + { + Name: name, + Value: &openapi.ResponseOrReference{ + Oneof: &openapi.ResponseOrReference_Response{ + Response: &openapi.Response{ + Description: desc, + Content: contentOrEmpty, + }, + }, + }, + }, + }, + } + } + + re := regexp.MustCompile(`:(\w+)`) + path = re.ReplaceAllString(path, `{$1}`) + + op := &openapi.Operation{ + Tags: []string{tagName}, + Description: description, + OperationId: operationID, + Parameters: parameters, + Responses: responses, + RequestBody: RequestBody, + } + if defaultHost != "" { + if !strings.HasPrefix(defaultHost, consts.URLDefaultPrefixHTTP) && !strings.HasPrefix(defaultHost, consts.URLDefaultPrefixHTTPS) { + defaultHost = consts.URLDefaultPrefixHTTP + defaultHost + } + op.Servers = append(op.Servers, &openapi.Server{Url: defaultHost}) + } + + return op, path +} + +func (g *OpenAPIGenerator) getResponseForMessage(d *openapi.Document, message *protogen.Message) (string, *openapi.MediaTypes) { + bodySchema := g.getSchemaByOption(message) + + var additionalProperties []*openapi.NamedMediaType + + if len(bodySchema.Properties.AdditionalProperties) > 0 { + refSchema := &openapi.NamedSchemaOrReference{ + Name: g.reflect.formatMessageName(message.Desc), + Value: &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: bodySchema}}, + } + ref := consts.ComponentSchemaPrefix + g.reflect.formatMessageName(message.Desc) + g.addSchemaToDocument(d, refSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ + Name: consts.ContentTypeJSON, + Value: &openapi.MediaType{ + Schema: &openapi.SchemaOrReference{ + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: ref}, + }, + }, + }, + }) + } + + content := &openapi.MediaTypes{ + AdditionalProperties: additionalProperties, + } + + return consts.StatusOK, content +} + +// addOperationToDocument adds an operation to the specified path/method. +func (g *OpenAPIGenerator) addOperationToDocument(d *openapi.Document, op *openapi.Operation, path string) { + var selectedPathItem *openapi.NamedPathItem + for _, namedPathItem := range d.Paths.Path { + if namedPathItem.Name == path { + selectedPathItem = namedPathItem + break + } + } + // If we get here, we need to create a path item. + if selectedPathItem == nil { + selectedPathItem = &openapi.NamedPathItem{Name: path, Value: &openapi.PathItem{}} + d.Paths.Path = append(d.Paths.Path, selectedPathItem) + } + // Set the operation on the specified method. + selectedPathItem.Value.Post = op +} + +func (g *OpenAPIGenerator) addPathsToDocument(d *openapi.Document, services []*protogen.Service) { + for _, service := range services { + annotationsCount := 0 + + for _, method := range service.Methods { + comment := g.filterCommentString(method.Comments.Leading) + inputMessage := method.Input + outputMessage := method.Output + operationID := string(service.Desc.Name()) + "_" + string(method.Desc.Name()) + path := "/" + string(method.Desc.Name()) + + annotationsCount++ + var host string + host = proto.GetExtension(method.Desc.Options(), api.E_Baseurl).(string) + + if host == "" { + host = proto.GetExtension(service.Desc.Options(), api.E_BaseDomain).(string) + } + op, path2 := g.buildOperation(d, operationID, string(service.Desc.Name()), comment, host, path, inputMessage, outputMessage) + // Merge any `Operation` annotations with the current + extOperation := proto.GetExtension(method.Desc.Options(), openapi.E_Operation) + + if extOperation != nil { + proto.Merge(op, extOperation.(*openapi.Operation)) + } + g.addOperationToDocument(d, op, path2) + } + if annotationsCount > 0 { + comment := g.filterCommentString(service.Comments.Leading) + d.Tags = append(d.Tags, &openapi.Tag{Name: string(service.Desc.Name()), Description: comment}) + } + } +} + +// addSchemaToDocument adds the schema to the document if required +func (g *OpenAPIGenerator) addSchemaToDocument(d *openapi.Document, schema *openapi.NamedSchemaOrReference) { + if common.Contains(g.generatedSchemas, schema.Name) { + return + } + g.generatedSchemas = append(g.generatedSchemas, schema.Name) + d.Components.Schemas.AdditionalProperties = append(d.Components.Schemas.AdditionalProperties, schema) +} + +// addSchemasForMessagesToDocument adds info from one file descriptor. +func (g *OpenAPIGenerator) addSchemasForMessagesToDocument(d *openapi.Document, messages []*protogen.Message) { + // For each message, generate a definition. + for _, message := range messages { + if message.Messages != nil { + g.addSchemasForMessagesToDocument(d, message.Messages) + } + + schemaName := g.reflect.formatMessageName(message.Desc) + + // Only generate this if we need it and haven't already generated it. + if !common.Contains(g.reflect.requiredSchemas, schemaName) || + common.Contains(g.generatedSchemas, schemaName) { + continue + } + + typeName := g.reflect.fullMessageTypeName(message.Desc) + messageDescription := g.filterCommentString(message.Comments.Leading) + + // `google.protobuf.Value` and `google.protobuf.Any` have special JSON transcoding + // so we can't just reflect on the message descriptor. + if typeName == ".google.protobuf.Value" { + g.addSchemaToDocument(d, wk.NewGoogleProtobufValueSchema(schemaName)) + continue + } else if typeName == ".google.protobuf.Any" { + g.addSchemaToDocument(d, wk.NewGoogleProtobufAnySchema(schemaName)) + continue + } else if typeName == ".google.rpc.Status" { + anySchemaName := g.reflect.formatMessageName(anyProtoDesc) + g.addSchemaToDocument(d, wk.NewGoogleProtobufAnySchema(anySchemaName)) + g.addSchemaToDocument(d, wk.NewGoogleRpcStatusSchema(schemaName, anySchemaName)) + continue + } + + // Build an array holding the fields of the message. + definitionProperties := &openapi.Properties{ + AdditionalProperties: make([]*openapi.NamedSchemaOrReference, 0), + } + + var required []string + for _, field := range message.Fields { + // Get the field description from the comments. + description := g.filterCommentString(field.Comments.Leading) + // Check the field annotations to see if this is a readonly or writeonly field. + inputOnly := false + outputOnly := false + extension := proto.GetExtension(field.Desc.Options(), annotations.E_FieldBehavior) + if extension != nil { + switch v := extension.(type) { + case []annotations.FieldBehavior: + for _, vv := range v { + switch vv { + case annotations.FieldBehavior_OUTPUT_ONLY: + outputOnly = true + case annotations.FieldBehavior_INPUT_ONLY: + inputOnly = true + case annotations.FieldBehavior_REQUIRED: + required = append(required, g.reflect.formatFieldName(field.Desc)) + } + } + default: + logs.Errorf("unsupported extension type %T", extension) + } + } + + // The field is either described by a reference or a schema. + fieldSchema := g.reflect.schemaOrReferenceForField(field.Desc) + if fieldSchema == nil { + continue + } + + // If this field has siblings and is a $ref now, create a new schema use `allOf` to wrap it + wrapperNeeded := inputOnly || outputOnly || description != "" + if wrapperNeeded { + if _, ok := fieldSchema.Oneof.(*openapi.SchemaOrReference_Reference); ok { + fieldSchema = &openapi.SchemaOrReference{Oneof: &openapi.SchemaOrReference_Schema{Schema: &openapi.Schema{ + AllOf: []*openapi.SchemaOrReference{fieldSchema}, + }}} + } + } + + if schema, ok := fieldSchema.Oneof.(*openapi.SchemaOrReference_Schema); ok { + schema.Schema.Description = description + schema.Schema.ReadOnly = outputOnly + schema.Schema.WriteOnly = inputOnly + + // Merge any `Property` annotations with the current + extProperty := proto.GetExtension(field.Desc.Options(), openapi.E_Property) + if extProperty != nil { + proto.Merge(schema.Schema, extProperty.(*openapi.Schema)) + } + } + + name := g.reflect.formatFieldName(field.Desc) + + definitionProperties.AdditionalProperties = append( + definitionProperties.AdditionalProperties, + &openapi.NamedSchemaOrReference{ + Name: name, + Value: fieldSchema, + }, + ) + } + + schema := &openapi.Schema{ + Type: consts.SchemaObjectType, + Description: messageDescription, + Properties: definitionProperties, + Required: required, + } + + // Merge any `Schema` annotations with the current + extSchema := proto.GetExtension(message.Desc.Options(), openapi.E_Schema) + if extSchema != nil { + proto.Merge(schema, extSchema.(*openapi.Schema)) + } + + // Add the schema to the components.schema list. + g.addSchemaToDocument(d, &openapi.NamedSchemaOrReference{ + Name: schemaName, + Value: &openapi.SchemaOrReference{ + Oneof: &openapi.SchemaOrReference_Schema{ + Schema: schema, + }, + }, + }) + } +} diff --git a/protoc-gen-rpc-swagger/generator/reflector.go b/protoc-gen-rpc-swagger/generator/reflector.go new file mode 100644 index 0000000..1ab640c --- /dev/null +++ b/protoc-gen-rpc-swagger/generator/reflector.go @@ -0,0 +1,239 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright 2020 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file may have been modified by CloudWeGo authors. All CloudWeGo + * Modifications are Copyright 2024 CloudWeGo Authors. + */ + +package generator + +import ( + "log" + "strings" + + "github.com/hertz-contrib/swagger-generate/common/consts" + common "github.com/hertz-contrib/swagger-generate/common/utils" + "github.com/hertz-contrib/swagger-generate/idl/protobuf/openapi" + wk "github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger/generator/wellknown" + "github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger/utils" + "google.golang.org/protobuf/reflect/protoreflect" +) + +type OpenAPIReflector struct { + conf Configuration + requiredSchemas []string // Names of schemas which are used through references. +} + +// NewOpenAPIReflector creates a new reflector. +func NewOpenAPIReflector(conf Configuration) *OpenAPIReflector { + return &OpenAPIReflector{ + conf: conf, + requiredSchemas: make([]string, 0), + } +} + +func (r *OpenAPIReflector) getMessageName(message protoreflect.MessageDescriptor) string { + prefix := "" + parent := message.Parent() + + if _, ok := parent.(protoreflect.MessageDescriptor); ok { + prefix = string(parent.Name()) + "_" + prefix + } + + return prefix + string(message.Name()) +} + +func (r *OpenAPIReflector) formatMessageName(message protoreflect.MessageDescriptor) string { + typeName := r.fullMessageTypeName(message) + + name := r.getMessageName(message) + if !*r.conf.FQSchemaNaming { + if typeName == ".google.protobuf.Value" { + name = consts.ProtobufValueName + } else if typeName == ".google.protobuf.Any" { + name = consts.ProtobufAnyName + } + } + + if *r.conf.Naming == "json" { + if len(name) > 1 { + name = strings.ToUpper(name[0:1]) + name[1:] + } + + if len(name) == 1 { + name = strings.ToLower(name) + } + } + + if *r.conf.FQSchemaNaming { + package_name := string(message.ParentFile().Package()) + name = package_name + "." + name + } + + return name +} + +func (r *OpenAPIReflector) formatFieldName(field protoreflect.FieldDescriptor) string { + if *r.conf.Naming == "proto" { + return string(field.Name()) + } + return field.JSONName() +} + +// fullMessageTypeName builds the full type name of a message. +func (r *OpenAPIReflector) fullMessageTypeName(message protoreflect.MessageDescriptor) string { + name := r.getMessageName(message) + return "." + string(message.ParentFile().Package()) + "." + name +} + +func (r *OpenAPIReflector) schemaReferenceForMessage(message protoreflect.MessageDescriptor) string { + schemaName := r.formatMessageName(message) + if !common.Contains(r.requiredSchemas, schemaName) { + r.requiredSchemas = append(r.requiredSchemas, schemaName) + } + return "#/components/schemas/" + schemaName +} + +// Returns a full schema for simple types, and a schema reference for complex types that reference +// the definition in `#/components/schemas/` +func (r *OpenAPIReflector) schemaOrReferenceForMessage(message protoreflect.MessageDescriptor) *openapi.SchemaOrReference { + typeName := r.fullMessageTypeName(message) + + switch typeName { + + case ".google.api.HttpBody": + return wk.NewGoogleApiHttpBodySchema() + + case ".google.protobuf.Timestamp": + return wk.NewGoogleProtobufTimestampSchema() + + case ".google.protobuf.Duration": + return wk.NewGoogleProtobufDurationSchema() + + case ".google.type.Date": + return wk.NewGoogleTypeDateSchema() + + case ".google.type.DateTime": + return wk.NewGoogleTypeDateTimeSchema() + + case ".google.protobuf.FieldMask": + return wk.NewGoogleProtobufFieldMaskSchema() + + case ".google.protobuf.Struct": + return wk.NewGoogleProtobufStructSchema() + + case ".google.protobuf.Empty": + // Empty is closer to JSON undefined than null, so ignore this field + return nil //&v3.SchemaOrReference{Oneof: &v3.SchemaOrReference_Schema{Schema: &v3.Schema{Type: "null"}}} + + case ".google.protobuf.BoolValue": + return wk.NewBooleanSchema() + + case ".google.protobuf.BytesValue": + return wk.NewBytesSchema() + + case ".google.protobuf.Int32Value", ".google.protobuf.UInt32Value": + return wk.NewIntegerSchema(utils.GetValueKind(message)) + + case ".google.protobuf.StringValue", ".google.protobuf.Int64Value", ".google.protobuf.UInt64Value": + return wk.NewStringSchema() + + case ".google.protobuf.FloatValue", ".google.protobuf.DoubleValue": + return wk.NewNumberSchema(utils.GetValueKind(message)) + + default: + ref := r.schemaReferenceForMessage(message) + return &openapi.SchemaOrReference{ + Oneof: &openapi.SchemaOrReference_Reference{ + Reference: &openapi.Reference{XRef: ref}, + }, + } + } +} + +func (r *OpenAPIReflector) schemaOrReferenceForField(field protoreflect.FieldDescriptor) *openapi.SchemaOrReference { + var kindSchema *openapi.SchemaOrReference + + kind := field.Kind() + + switch kind { + + case protoreflect.MessageKind: + if field.IsMap() { + // This means the field is a map, for example: + // map map_field = 1; + // + // The map ends up getting converted into something like this: + // message MapFieldEntry { + // string key = 1; + // value_type value = 2; + // } + // + // repeated MapFieldEntry map_field = N; + // + // So we need to find the `value` field in the `MapFieldEntry` message and + // then return a MapFieldEntry schema using the schema for the `value` field + return wk.NewGoogleProtobufMapFieldEntrySchema(r.schemaOrReferenceForField(field.MapValue())) + } else { + kindSchema = r.schemaOrReferenceForMessage(field.Message()) + } + + case protoreflect.StringKind: + kindSchema = wk.NewStringSchema() + + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Uint32Kind, + protoreflect.Sfixed32Kind, protoreflect.Fixed32Kind: + kindSchema = wk.NewIntegerSchema(kind.String()) + + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind, + protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind: + kindSchema = wk.NewStringSchema() + + case protoreflect.EnumKind: + kindSchema = wk.NewEnumSchema(*&r.conf.EnumType, field) + + case protoreflect.BoolKind: + kindSchema = wk.NewBooleanSchema() + + case protoreflect.FloatKind, protoreflect.DoubleKind: + kindSchema = wk.NewNumberSchema(kind.String()) + + case protoreflect.BytesKind: + kindSchema = wk.NewBytesSchema() + + default: + log.Printf("(TODO) Unsupported field type: %+v", r.fullMessageTypeName(field.Message())) + } + + if field.IsList() { + kindSchema = wk.NewListSchema(kindSchema) + } + + return kindSchema +} diff --git a/protoc-gen-rpc-swagger/generator/server_gen.go b/protoc-gen-rpc-swagger/generator/server_gen.go new file mode 100644 index 0000000..83234da --- /dev/null +++ b/protoc-gen-rpc-swagger/generator/server_gen.go @@ -0,0 +1,127 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package generator + +import ( + "bytes" + "errors" + "fmt" + "io/ioutil" + "path/filepath" + "regexp" + "strings" + "text/template" + + "github.com/hertz-contrib/swagger-generate/common/consts" + "github.com/hertz-contrib/swagger-generate/common/tpl" + "github.com/hertz-contrib/swagger-generate/common/utils" + "google.golang.org/protobuf/compiler/protogen" +) + +type ServerConfiguration struct { + KitexAddr *string +} + +type ServerGenerator struct { + IdlPath string + KitexAddr string +} + +func NewServerGenerator(conf ServerConfiguration, inputFiles []*protogen.File) (*ServerGenerator, error) { + kitexAddr := conf.KitexAddr + if kitexAddr == nil { + *kitexAddr = consts.DefaultKitexAddr + } + + var idlPath string + var genFiles []*protogen.File + for _, f := range inputFiles { + if f.Generate { + genFiles = append(genFiles, f) + } + } + if len(genFiles) > 1 { + return nil, errors.New("only one .proto file is supported for generation swagger") + } else if len(genFiles) == 1 { + idlPath = genFiles[0].Desc.Path() + } else { + return nil, errors.New("no .proto files marked for generation") + } + // Check if Hertz and Kitex addresses are valid (basic validation) + if err := validateAddress(*kitexAddr); err != nil { + return nil, fmt.Errorf("invalid Kitex address: %w", err) + } + + return &ServerGenerator{ + IdlPath: idlPath, + KitexAddr: *kitexAddr, + }, nil +} + +func validateAddress(addr string) error { + if addr == "" { + return errors.New("address cannot be empty") + } + if !strings.Contains(addr, ":") { + return errors.New("address must include a port (e.g., '127.0.0.1:8080')") + } + return nil +} + +func (g *ServerGenerator) Generate(outputFile *protogen.GeneratedFile) error { + filePath := filepath.Join(filepath.Dir(g.IdlPath), consts.DefaultOutputSwaggerFile) + if utils.FileExists(filePath) { + updatedContent, err := updateVariables(filePath, g.KitexAddr, g.IdlPath) + if err != nil { + return errors.New("failed to update variables in the existing file") + } + if _, err = outputFile.Write([]byte(updatedContent)); err != nil { + return errors.New("failed to write output file") + } + } else { + tmpl, err := template.New("server").Delims("{{", "}}").Parse(consts.CodeGenerationCommentPbRpc + "\n" + tpl.ServerTemplateRpcPb) + if err != nil { + return fmt.Errorf("failed to parse template: %w", err) + } + + var buf bytes.Buffer + err = tmpl.Execute(&buf, g) + if err != nil { + return fmt.Errorf("failed to execute template: %w", err) + } + + if _, err = outputFile.Write(buf.Bytes()); err != nil { + return fmt.Errorf("failed to write output file: %v", err) + } + } + return nil +} + +func updateVariables(filePath, newKitexAddr, newIdlPath string) (string, error) { + content, err := ioutil.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("failed to read file: %v", err) + } + + kitexAddrPattern := regexp.MustCompile(`kitexAddr\s*=\s*"(.*?)"`) + idlPathPattern := regexp.MustCompile(`idlFile\s*=\s*"(.*?)"`) + + updatedContent := kitexAddrPattern.ReplaceAllString(string(content), fmt.Sprintf(`kitexAddr = "%s"`, newKitexAddr)) + updatedContent = idlPathPattern.ReplaceAllString(updatedContent, fmt.Sprintf(`idlFile = "%s"`, newIdlPath)) + + return updatedContent, nil +} diff --git a/protoc-gen-rpc-swagger/generator/wellknown/schemas.go b/protoc-gen-rpc-swagger/generator/wellknown/schemas.go new file mode 100644 index 0000000..47ded85 --- /dev/null +++ b/protoc-gen-rpc-swagger/generator/wellknown/schemas.go @@ -0,0 +1,347 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright 2020 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file may have been modified by CloudWeGo authors. All CloudWeGo + * Modifications are Copyright 2024 CloudWeGo Authors. + */ + +package wellknown + +import ( + v3 "github.com/hertz-contrib/swagger-generate/idl/protobuf/openapi" + "google.golang.org/protobuf/reflect/protoreflect" +) + +func NewStringSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string"}, + }, + } +} + +func NewBooleanSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "boolean"}, + }, + } +} + +func NewBytesSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string", Format: "bytes"}, + }, + } +} + +func NewIntegerSchema(format string) *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "integer", Format: format}, + }, + } +} + +func NewNumberSchema(format string) *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "number", Format: format}, + }, + } +} + +func NewEnumSchema(enum_type *string, field protoreflect.FieldDescriptor) *v3.SchemaOrReference { + schema := &v3.Schema{Format: "enum"} + if enum_type != nil && *enum_type == "string" { + schema.Type = "string" + schema.Enum = make([]*v3.Any, 0, field.Enum().Values().Len()) + for i := 0; i < field.Enum().Values().Len(); i++ { + schema.Enum = append(schema.Enum, &v3.Any{ + Yaml: string(field.Enum().Values().Get(i).Name()), + }) + } + } else { + schema.Type = "integer" + } + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: schema, + }, + } +} + +func NewListSchema(item_schema *v3.SchemaOrReference) *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "array", + Items: &v3.ItemsItem{SchemaOrReference: []*v3.SchemaOrReference{item_schema}}, + }, + }, + } +} + +// google.api.HttpBody will contain POST body data +// This is based on how Envoy handles google.api.HttpBody +func NewGoogleApiHttpBodySchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string"}, + }, + } +} + +// google.protobuf.Timestamp is serialized as a string +func NewGoogleProtobufTimestampSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string", Format: "date-time"}, + }, + } +} + +// google.protobuf.Duration is serialized as a string +func NewGoogleProtobufDurationSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + // From: https://github.com/protocolbuffers/protobuf/blob/ece5ef6b9b6fa66ef4638335612284379ee4548f/src/google/protobuf/duration.proto + // In JSON format, the Duration type is encoded as a string rather than an + // object, where the string ends in the suffix "s" (indicating seconds) and + // is preceded by the number of seconds, with nanoseconds expressed as + // fractional seconds. For example, 3 seconds with 0 nanoseconds should be + // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should + // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 + // microsecond should be expressed in JSON format as "3.000001s". + // + // The fields of message google.protobuf.Duration are further described as: + // "int64 seconds" + // Signed seconds of the span of time. Must be from -315,576,000,000 + // to +315,576,000,000 inclusive. Note: these bounds are computed from: + // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + // `int32 nanos` + // Signed fractions of a second at nanosecond resolution of the span + // of time. Durations less than one second are represented with a 0 + // `seconds` field and a positive or negative `nanos` field. For durations + // of one second or more, a non-zero value for the `nanos` field must be + // of the same sign as the `seconds` field. Must be from -999,999,999 + // to +999,999,999 inclusive. + // + // This leads to the regex below limiting range from -315.576,000,000s to 315,576,000,000s + // allowing -0.999,999,999s to 0.999,999,999s in the floating precision range. + // That full range cannot be expressed precisely in float64 as demonstrated in + // the example at https://go.dev/play/p/XNtuhwdyu8Y for your reference. + // So the well known type google.protobuf.Duration needs a string. + // + // Please note that JSON schemas duration format is NOT the same, as that uses + // a different syntax starting with "P", supports daylight saving times and other + // different features, so it is NOT compatible. + Schema: &v3.Schema{ + Type: "string", + Pattern: `^-?(?:0|[1-9][0-9]{0,11})(?:\.[0-9]{1,9})?s$`, + Description: "Represents a a duration between -315,576,000,000s and 315,576,000,000s (around 10000 years). Precision is in nanoseconds. 1 nanosecond is represented as 0.000000001s", + }, + }, + } +} + +// google.type.Date is serialized as a string +func NewGoogleTypeDateSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string", Format: "date"}, + }, + } +} + +// google.type.DateTime is serialized as a string +func NewGoogleTypeDateTimeSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string", Format: "date-time"}, + }, + } +} + +// google.protobuf.FieldMask masks is serialized as a string +func NewGoogleProtobufFieldMaskSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "string", Format: "field-mask"}, + }, + } +} + +// google.protobuf.Struct is equivalent to a JSON object +func NewGoogleProtobufStructSchema() *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{Type: "object"}, + }, + } +} + +// google.protobuf.Value is handled specially +// See here for the details on the JSON mapping: +// +// https://developers.google.com/protocol-buffers/docs/proto3#json +// +// and here: +// +// https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value +func NewGoogleProtobufValueSchema(name string) *v3.NamedSchemaOrReference { + return &v3.NamedSchemaOrReference{ + Name: name, + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Description: "Represents a dynamically typed value which can be either null, a number, a string, a boolean, a recursive struct value, or a list of values.", + }, + }, + }, + } +} + +// google.protobuf.Any is handled specially +// See here for the details on the JSON mapping: +// +// https://developers.google.com/protocol-buffers/docs/proto3#json +func NewGoogleProtobufAnySchema(name string) *v3.NamedSchemaOrReference { + return &v3.NamedSchemaOrReference{ + Name: name, + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "object", + Description: "Contains an arbitrary serialized message along with a @type that describes the type of the serialized message.", + Properties: &v3.Properties{ + AdditionalProperties: []*v3.NamedSchemaOrReference{ + { + Name: "@type", + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "string", + Description: "The type of the serialized message.", + }, + }, + }, + }, + }, + }, + AdditionalProperties: &v3.AdditionalPropertiesItem{ + Oneof: &v3.AdditionalPropertiesItem_Boolean{ + Boolean: true, + }, + }, + }, + }, + }, + } +} + +// google.rpc.Status is handled specially +func NewGoogleRpcStatusSchema(name, any_name string) *v3.NamedSchemaOrReference { + return &v3.NamedSchemaOrReference{ + Name: name, + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "object", + Description: "The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).", + Properties: &v3.Properties{ + AdditionalProperties: []*v3.NamedSchemaOrReference{ + { + Name: "code", + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "integer", + Format: "int32", + Description: "The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].", + }, + }, + }, + }, + { + Name: "message", + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "string", + Description: "A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.", + }, + }, + }, + }, + { + Name: "details", + Value: &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "array", + Items: &v3.ItemsItem{ + SchemaOrReference: []*v3.SchemaOrReference{ + { + Oneof: &v3.SchemaOrReference_Reference{ + Reference: &v3.Reference{ + XRef: "#/components/schemas/" + any_name, + }, + }, + }, + }, + }, + Description: "A list of messages that carry the error details. There is a common set of message types for APIs to use.", + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func NewGoogleProtobufMapFieldEntrySchema(value_field_schema *v3.SchemaOrReference) *v3.SchemaOrReference { + return &v3.SchemaOrReference{ + Oneof: &v3.SchemaOrReference_Schema{ + Schema: &v3.Schema{ + Type: "object", + AdditionalProperties: &v3.AdditionalPropertiesItem{ + Oneof: &v3.AdditionalPropertiesItem_SchemaOrReference{ + SchemaOrReference: value_field_schema, + }, + }, + }, + }, + } +} diff --git a/protoc-gen-rpc-swagger/go.mod b/protoc-gen-rpc-swagger/go.mod new file mode 100644 index 0000000..81e5dd0 --- /dev/null +++ b/protoc-gen-rpc-swagger/go.mod @@ -0,0 +1,77 @@ +module github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger + +go 1.18 + +require ( + github.com/bytedance/gopkg v0.1.1 + github.com/cloudwego/hertz v0.9.3 + github.com/cloudwego/hertz/cmd/hz v0.9.1 + github.com/cloudwego/kitex v0.10.3 + github.com/hertz-contrib/cors v0.1.0 + github.com/hertz-contrib/swagger v0.1.0 + github.com/hertz-contrib/swagger-generate v0.0.0 + github.com/swaggo/files v1.0.1 + google.golang.org/genproto/googleapis/api v0.0.0-20240730163845-b1a4ccb954bf + google.golang.org/protobuf v1.34.2 +) + +require ( + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/apache/thrift v0.17.0 // indirect + github.com/bytedance/go-tagexpr/v2 v2.9.2 // indirect + github.com/bytedance/sonic v1.12.0 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/configmanager v0.2.2 // indirect + github.com/cloudwego/dynamicgo v0.2.9 // indirect + github.com/cloudwego/fastpb v0.0.4 // indirect + github.com/cloudwego/frugal v0.1.15 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/cloudwego/localsession v0.0.2 // indirect + github.com/cloudwego/netpoll v0.6.3 // indirect + github.com/cloudwego/runtimex v0.1.0 // indirect + github.com/cloudwego/thriftgo v0.3.15 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fatih/structtag v1.2.0 // indirect + github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/go-openapi/jsonpointer v0.20.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/spec v0.20.9 // indirect + github.com/go-openapi/swag v0.22.4 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 // indirect + github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 // indirect + github.com/henrylee2cn/ameda v1.4.10 // indirect + github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect + github.com/jhump/protoreflect v1.12.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.5 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/gls v0.0.0-20220109145502-612d0167dce5 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/nyaruka/phonenumbers v1.0.55 // indirect + github.com/oleiade/lane v1.0.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect + github.com/swaggo/swag v1.16.1 // indirect + github.com/tidwall/gjson v1.14.4 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + golang.org/x/arch v0.2.0 // indirect + golang.org/x/net v0.27.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.16.0 // indirect + golang.org/x/tools v0.22.0 // indirect + google.golang.org/genproto v0.0.0-20240725223205-93522f1f2a9f // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +replace github.com/apache/thrift v0.17.0 => github.com/apache/thrift v0.13.0 + +replace github.com/hertz-contrib/swagger-generate => ../../swagger-generate diff --git a/protoc-gen-rpc-swagger/go.sum b/protoc-gen-rpc-swagger/go.sum new file mode 100644 index 0000000..56dba4b --- /dev/null +++ b/protoc-gen-rpc-swagger/go.sum @@ -0,0 +1,508 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= +git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= +github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= +github.com/ajstarks/deck v0.0.0-20200831202436-30c9fc6549a9/go.mod h1:JynElWSGnm/4RlzPXRlREEwqTHAN3T56Bv2ITsFT3gY= +github.com/ajstarks/deck/generate v0.0.0-20210309230005-c3f852c02e19/go.mod h1:T13YZdzov6OU0A1+RfKZiZN9ca6VeKdBdyDV+BY97Tk= +github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= +github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= +github.com/apache/thrift v0.13.0 h1:5hryIiq9gtn+MiLVn0wP37kb/uTeRZgN08WoCsAhIhI= +github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/bytedance/go-tagexpr/v2 v2.9.2 h1:QySJaAIQgOEDQBLS3x9BxOWrnhqu5sQ+f6HaZIxD39I= +github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= +github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= +github.com/bytedance/gopkg v0.0.0-20230728082804-614d0af6619b/go.mod h1:FtQG3YbQG9L/91pbKSw787yBQPutC+457AvDW77fgUQ= +github.com/bytedance/gopkg v0.0.0-20240507064146-197ded923ae3/go.mod h1:FtQG3YbQG9L/91pbKSw787yBQPutC+457AvDW77fgUQ= +github.com/bytedance/gopkg v0.0.0-20240514070511-01b2cbcf35e1/go.mod h1:FtQG3YbQG9L/91pbKSw787yBQPutC+457AvDW77fgUQ= +github.com/bytedance/gopkg v0.1.1 h1:3azzgSkiaw79u24a+w9arfH8OfnQQ4MHUt9lJFREEaE= +github.com/bytedance/gopkg v0.1.1/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/mockey v1.2.1/go.mod h1:+Jm/fzWZAuhEDrPXVjDf/jLM2BlLXJkwk94zf2JZ3X4= +github.com/bytedance/mockey v1.2.12 h1:aeszOmGw8CPX8CRx1DZ/Glzb1yXvhjDh6jdFBNZjsU4= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic v1.11.8/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic v1.12.0 h1:YGPgxF9xzaCNvd/ZKdQ28yRovhfMFZQjuk6fKBzZ3ls= +github.com/bytedance/sonic v1.12.0/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chzyer/logex v1.2.0/go.mod h1:9+9sk7u7pGNWYMkh0hdiL++6OeibzJccyQU4p4MedaY= +github.com/chzyer/readline v1.5.0/go.mod h1:x22KAscuvRqlLoK9CsoYsmxoXZMMFVyOl86cAH8qUic= +github.com/chzyer/test v0.0.0-20210722231415-061457976a23/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/configmanager v0.2.2 h1:sVrJB8gWYTlPV2OS3wcgJSO9F2/9Zbkmcm1Z7jempOU= +github.com/cloudwego/configmanager v0.2.2/go.mod h1:ppiyU+5TPLonE8qMVi/pFQk2eL3Q4P7d4hbiNJn6jwI= +github.com/cloudwego/dynamicgo v0.2.9 h1:MHGyGmdFT8iMOsM5S9iutjZB0csu2LupsTTHyi6a8pY= +github.com/cloudwego/dynamicgo v0.2.9/go.mod h1:F3jlbPmlNzhcuDMXwZoBJ7rJKpg2iE+TnIy9pSJiGzs= +github.com/cloudwego/fastpb v0.0.4 h1:/ROVVfoFtpfc+1pkQLzGs+azjxUbSOsAqSY4tAAx4mg= +github.com/cloudwego/fastpb v0.0.4/go.mod h1:/V13XFTq2TUkxj2qWReV8MwfPC4NnPcy6FsrojnsSG0= +github.com/cloudwego/frugal v0.1.15 h1:LC55UJKhQPMFVjDPbE+LJcF7etZjSx6uokG1tk0wPK0= +github.com/cloudwego/frugal v0.1.15/go.mod h1:26kU1r18vA8vRg12c66XPDlfv1GQHDbE1RpusipXfcI= +github.com/cloudwego/hertz v0.6.2/go.mod h1:2em2hGREvCBawsTQcQxyWBGVlCeo+N1pp2q0HkkbwR0= +github.com/cloudwego/hertz v0.9.3 h1:uajvLn6LjEPjUqN/ewUZtWoRQWa2es2XTELdqDlOYMw= +github.com/cloudwego/hertz v0.9.3/go.mod h1:gGVUfJU/BOkJv/ZTzrw7FS7uy7171JeYIZvAyV3wS3o= +github.com/cloudwego/hertz/cmd/hz v0.9.1 h1:v75TueFIZhTgYYnoM+6VxKHu58ZS3HJ+Qp4T07UYcKk= +github.com/cloudwego/hertz/cmd/hz v0.9.1/go.mod h1:6SroAwvZkyL54CiPANDkTR3YoX2MY4ZOW1+gtmWhRJE= +github.com/cloudwego/iasm v0.0.9/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cloudwego/kitex v0.10.3 h1:L3JRkb25oXMf1ROslQNY7E9EpaUBBjJWwjGfkQERJ+k= +github.com/cloudwego/kitex v0.10.3/go.mod h1:6wYnJc0TpKnHwM8/Fcy2YrQNyrlmpMYP0y5ADZrqYsc= +github.com/cloudwego/localsession v0.0.2 h1:N9/IDtCPj1fCL9bCTP+DbXx3f40YjVYWcwkJG0YhQkY= +github.com/cloudwego/localsession v0.0.2/go.mod h1:kiJxmvAcy4PLgKtEnPS5AXed3xCiXcs7Z+KBHP72Wv8= +github.com/cloudwego/netpoll v0.3.1/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= +github.com/cloudwego/netpoll v0.6.3 h1:t+ndlwBFjQZimUj3ul31DwI45t18eOr2pcK3juZZm+E= +github.com/cloudwego/netpoll v0.6.3/go.mod h1:kaqvfZ70qd4T2WtIIpCOi5Cxyob8viEpzLhCrTrz3HM= +github.com/cloudwego/runtimex v0.1.0 h1:HG+WxWoj5/CDChDZ7D99ROwvSMkuNXAqt6hnhTTZDiI= +github.com/cloudwego/runtimex v0.1.0/go.mod h1:23vL/HGV0W8nSCHbe084AgEBdDV4rvXenEUMnUNvUd8= +github.com/cloudwego/thriftgo v0.1.7/go.mod h1:LzeafuLSiHA9JTiWC8TIMIq64iadeObgRUhmVG1OC/w= +github.com/cloudwego/thriftgo v0.3.6/go.mod h1:29ukiySoAMd0vXMYIduAY9dph/7dmChvOS11YLotFb8= +github.com/cloudwego/thriftgo v0.3.15 h1:yB/DDGjeSjliyidMVBjKhGl9RgE4M8iVIz5dKpAIyUs= +github.com/cloudwego/thriftgo v0.3.15/go.mod h1:R4a+4aVDI0V9YCTfpNgmvbkq/9ThKgF7Om8Z0I36698= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= +github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= +github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/go-fonts/dejavu v0.1.0/go.mod h1:4Wt4I4OU2Nq9asgDCteaAaWZOV24E+0/Pwo0gppep4g= +github.com/go-fonts/latin-modern v0.2.0/go.mod h1:rQVLdDMK+mK1xscDwsqM5J8U2jrRa3T0ecnM9pNujks= +github.com/go-fonts/liberation v0.1.1/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/liberation v0.2.0/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-latex/latex v0.0.0-20210118124228-b3d85cf34e07/go.mod h1:CO1AlKB2CSIqUrmQPqA0gdRIlnLEY0gK5JGjh37zN5U= +github.com/go-latex/latex v0.0.0-20210823091927-c0d11ff05a81/go.mod h1:SX0U8uGpxhq9o2S/CELCSUxEWWAuoCUcVCQWv7G2OCk= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonpointer v0.20.0 h1:ESKJdU9ASRfaPNOPRx12IUyA1vn3R9GiE3KYD14BXdQ= +github.com/go-openapi/jsonpointer v0.20.0/go.mod h1:6PGzBjjIIumbLYysB73Klnms1mwnU4G3YHOECG3CedA= +github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/spec v0.20.9 h1:xnlYNQAwKd2VQRRfwTEI0DcK+2cbuvI/0c7jx3gA8/8= +github.com/go-openapi/spec v0.20.9/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= +github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-pdf/fpdf v0.5.0/go.mod h1:HzcnA+A23uwogo0tp9yU+l3V+KXhiESpt1PMayhOh5M= +github.com/go-pdf/fpdf v0.6.0/go.mod h1:HzcnA+A23uwogo0tp9yU+l3V+KXhiESpt1PMayhOh5M= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49 h1:0VpGH+cDhbDtdcweoyCVsF3fhN8kejK6rFe/2FFX2nU= +github.com/google/gnostic-models v0.6.9-0.20230804172637-c7be7c783f49/go.mod h1:BkkQ4L1KS1xMt2aWSPStnn55ChGC0DPOn2FQYj+f25M= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20220608213341-c488b8fa1db3/go.mod h1:gSuNB+gJaOiQKLEZ+q+PK9Mq3SOzhRcw2GsGS/FhYDk= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= +github.com/hashicorp/go-version v1.5.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/henrylee2cn/ameda v1.4.8/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= +github.com/henrylee2cn/ameda v1.4.10 h1:JdvI2Ekq7tapdPsuhrc4CaFiqw6QXFvZIULWJgQyCAk= +github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= +github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 h1:yE9ULgp02BhYIrO6sdV/FPe0xQM6fNHkVQW2IAymfM0= +github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= +github.com/hertz-contrib/cors v0.1.0 h1:PQ5mATygSMzTlYtfyMyHjobYoJeHKe2Qt3tcAOgbI6E= +github.com/hertz-contrib/cors v0.1.0/go.mod h1:VPReoq+Rvu/lZOfpp5CcX3x4mpZUc3EpSXBcVDcbvOc= +github.com/hertz-contrib/swagger v0.1.0 h1:FlnMPRHuvAt/3pt3KCQRZ6RH1g/agma9SU70Op2Pb58= +github.com/hertz-contrib/swagger v0.1.0/go.mod h1:Bt5i+Nyo7bGmYbuEfMArx7raf1oK+nWVgYbEvhpICKE= +github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= +github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/ianlancetaylor/demangle v0.0.0-20220319035150-800ac71e25c2/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= +github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= +github.com/jhump/gopoet v0.0.0-20190322174617-17282ff210b3/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= +github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+UPUI= +github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ= +github.com/jhump/protoreflect v1.8.2/go.mod h1:7GcYQDdMU/O/BBrl/cX6PNHpXh6cenjd8pneu5yW7Tg= +github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E= +github.com/jhump/protoreflect v1.12.0 h1:1NQ4FpWMgn3by/n1X0fbeKEUxP1wBt7+Oitpv01HR10= +github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= +github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/gls v0.0.0-20220109145502-612d0167dce5 h1:uiS4zKYKJVj5F3ID+5iylfKPsEQmBEOucSD9Vgmn0i0= +github.com/modern-go/gls v0.0.0-20220109145502-612d0167dce5/go.mod h1:I8AX+yW//L8Hshx6+a1m3bYkwXkpsVjA2795vP4f4oQ= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nishanths/predeclared v0.0.0-20200524104333-86fad755b4d3/go.mod h1:nt3d53pc1VYcphSCIaYAJtnPYnr3Zyn8fMq2wvPGPso= +github.com/nyaruka/phonenumbers v1.0.55 h1:bj0nTO88Y68KeUQ/n3Lo2KgK7lM1hF7L9NFuwcCl3yg= +github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= +github.com/oleiade/lane v1.0.1 h1:hXofkn7GEOubzTwNpeL9MaNy8WxolCYb9cInAIeqShU= +github.com/oleiade/lane v1.0.1/go.mod h1:IyTkraa4maLfjq/GmHR+Dxb4kCMtEGeb+qmhlrQ5Mk4= +github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= +github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= +github.com/ruudk/golang-pdf417 v0.0.0-20201230142125-a7e3863a1245/go.mod h1:pQAZKsJ8yyVxGRWYNEm9oFB8ieLgKFnamEyDmSA0BRk= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= +github.com/swaggo/swag v1.16.1 h1:fTNRhKstPKxcnoKsytm4sahr8FaYzUcT7i1/3nd/fBg= +github.com/swaggo/swag v1.16.1/go.mod h1:9/LMvHycG3NFHfR6LwvikHv5iFvmPADQ359cKikGxto= +github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/urfave/cli/v2 v2.23.0/go.mod h1:1CNUng3PtjQMtRzJO4FMXBQvkGtuYRxxiR9xMa7jMwI= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.2.0 h1:W1sUEHXiJTfjaFJ5SLo0N6lZn+0eO5gWD1MFeTGqQEY= +golang.org/x/arch v0.2.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE= +golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210216034530-4410531fe030/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210607152325-775e3b0c77b9/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20210628002857-a66eb6448b8d/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= +golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210304124612-50617c2ba197/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220110181412-a018aaa089fe/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200522201501-cb1345f3a375/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA= +golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= +gonum.org/v1/gonum v0.9.3/go.mod h1:TZumC3NeyVQskjXqmyWt4S3bINhy7B4eYwW69EbyX+0= +gonum.org/v1/gonum v0.12.0/go.mod h1:73TDxJfAAHeA8Mk9mf8NlIppyhQNo5GLTcYeqgo2lvY= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= +gonum.org/v1/plot v0.9.0/go.mod h1:3Pcqqmp6RHvJI72kgb8fThyUnav364FOsdDo2aGW5lY= +gonum.org/v1/plot v0.10.1/go.mod h1:VZW5OlhkL1mysU9vaqNHnsy86inf6Ot+jB3r+BczCEo= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20240725223205-93522f1f2a9f h1:htT2I9bZvGm+110zq8bIErMX+WgBWxCzV3ChwbvnKnc= +google.golang.org/genproto v0.0.0-20240725223205-93522f1f2a9f/go.mod h1:Sk3mLpoDFTAp6R4OvlcUgaG4ISTspKeFsIAXMn9Bm4Y= +google.golang.org/genproto/googleapis/api v0.0.0-20240730163845-b1a4ccb954bf h1:GillM0Ef0pkZPIB+5iO6SDK+4T9pf6TpaYR6ICD5rVE= +google.golang.org/genproto/googleapis/api v0.0.0-20240730163845-b1a4ccb954bf/go.mod h1:OFMYQFHJ4TM3JRlWDZhJbZfra2uqc3WLBZiaaqP4DtU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf h1:liao9UHurZLtiEwBgT9LMOnKYsHze6eA6w1KQCMVN2Q= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240730163845-b1a4ccb954bf/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.25.1-0.20200805231151-a709e31e5d12/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.1.3/go.mod h1:NgwopIslSNH47DimFoV78dnkksY2EFtX0ajyb3K/las= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/protoc-gen-rpc-swagger/main.go b/protoc-gen-rpc-swagger/main.go new file mode 100644 index 0000000..aa30060 --- /dev/null +++ b/protoc-gen-rpc-swagger/main.go @@ -0,0 +1,100 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright 2020 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file may have been modified by CloudWeGo authors. All CloudWeGo + * Modifications are Copyright 2024 CloudWeGo Authors. + */ + +package main + +import ( + "flag" + "path/filepath" + "strings" + + "github.com/hertz-contrib/swagger-generate/common/consts" + "github.com/hertz-contrib/swagger-generate/protoc-gen-rpc-swagger/generator" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/types/pluginpb" +) + +var flags flag.FlagSet + +func main() { + conf := generator.Configuration{ + Version: flags.String("version", "3.0.3", "version number text, e.g. 1.2.3"), + Title: flags.String("title", "", "name of the API"), + Description: flags.String("description", "", "description of the API"), + Naming: flags.String("naming", "json", `naming convention. Use "proto" for passing names directly from the proto files`), + FQSchemaNaming: flags.Bool("fq_schema_naming", false, `schema naming convention. If "true", generates fully-qualified schema names by prefixing them with the proto message package name`), + EnumType: flags.String("enum_type", "integer", `type for enum serialization. Use "string" for string-based serialization`), + OutputMode: flags.String("output_mode", "merged", `output generation mode. By default, a single openapi.yaml is generated at the out folder. Use "source_relative' to generate a separate '[inputfile].openapi.yaml' next to each '[inputfile].proto'.`), + } + + serverConf := generator.ServerConfiguration{ + KitexAddr: flags.String("kitex_addr", "127.0.0.1:8888", "kitex server address"), + } + + opts := protogen.Options{ + ParamFunc: flags.Set, + } + + opts.Run(func(plugin *protogen.Plugin) error { + // Enable "optional" keyword in front of type (e.g. optional string label = 1;) + plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL) + if *conf.OutputMode == "source_relative" { + for _, file := range plugin.Files { + if !file.Generate { + continue + } + outfileName := strings.TrimSuffix(file.Desc.Path(), filepath.Ext(file.Desc.Path())) + "." + consts.DefaultOutputYamlFile + outputFile := plugin.NewGeneratedFile(outfileName, "") + gen := generator.NewOpenAPIGenerator(plugin, conf, []*protogen.File{file}) + if err := gen.Run(outputFile); err != nil { + return err + } + } + } else { + outputFile := plugin.NewGeneratedFile(consts.DefaultOutputYamlFile, "") + gen := generator.NewOpenAPIGenerator(plugin, conf, plugin.Files) + if err := gen.Run(outputFile); err != nil { + return err + } + } + outputFile := plugin.NewGeneratedFile(consts.DefaultOutputSwaggerFile, "") + gen, err := generator.NewServerGenerator(serverConf, plugin.Files) + if err != nil { + return err + } + if err = gen.Generate(outputFile); err != nil { + return err + } + return nil + }) +} diff --git a/protoc-gen-rpc-swagger/utils/utils.go b/protoc-gen-rpc-swagger/utils/utils.go new file mode 100644 index 0000000..614b548 --- /dev/null +++ b/protoc-gen-rpc-swagger/utils/utils.go @@ -0,0 +1,48 @@ +/* + * Copyright 2024 CloudWeGo Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright 2020 Google LLC. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file may have been modified by CloudWeGo authors. All CloudWeGo + * Modifications are Copyright 2024 CloudWeGo Authors. + */ + +package utils + +import ( + "google.golang.org/protobuf/reflect/protoreflect" +) + +func GetValueKind(message protoreflect.MessageDescriptor) string { + valueField := getValueField(message) + return valueField.Kind().String() +} + +func getValueField(message protoreflect.MessageDescriptor) protoreflect.FieldDescriptor { + fields := message.Fields() + return fields.ByName("value") +} diff --git a/thrift-gen-http-swagger/example/swagger/openapi.yaml b/thrift-gen-http-swagger/example/swagger/openapi.yaml index f2d558e..47851a1 100644 --- a/thrift-gen-http-swagger/example/swagger/openapi.yaml +++ b/thrift-gen-http-swagger/example/swagger/openapi.yaml @@ -25,14 +25,7 @@ paths: content: application/json: schema: - type: object - properties: - body: - type: string - description: 'field: body描述' - body1: - type: string - description: 'field: body1描述' + $ref: '#/components/schemas/BodyReqBody' responses: "200": description: HelloResp @@ -56,32 +49,10 @@ paths: content: multipart/form-data: schema: - title: Hello - request - required: - - form1 - type: object - properties: - form1: - title: this is an override field schema title - maxLength: 255 - type: string - form3: - $ref: '#/components/schemas/InnerForm' - description: Hello - request + $ref: '#/components/schemas/FormReqForm' application/x-www-form-urlencoded: schema: - title: Hello - request - required: - - form1 - type: object - properties: - form1: - title: this is an override field schema title - maxLength: 255 - type: string - form3: - $ref: '#/components/schemas/InnerForm' - description: Hello - request + $ref: '#/components/schemas/FormReqForm' responses: "200": description: HelloResp @@ -214,6 +185,28 @@ paths: - url: http://127.0.0.1:8888 components: schemas: + BodyReqBody: + type: object + properties: + body: + type: string + description: 'field: body描述' + body1: + type: string + description: 'field: body1描述' + FormReqForm: + title: Hello - request + required: + - form1 + type: object + properties: + form1: + title: this is an override field schema title + maxLength: 255 + type: string + form3: + $ref: '#/components/schemas/InnerForm' + description: Hello - request HelloRespBody: title: Hello - response required: diff --git a/thrift-gen-http-swagger/generator/openapi_gen.go b/thrift-gen-http-swagger/generator/openapi_gen.go index 0d37651..69de73c 100644 --- a/thrift-gen-http-swagger/generator/openapi_gen.go +++ b/thrift-gen-http-swagger/generator/openapi_gen.go @@ -442,28 +442,47 @@ func (g *OpenAPIGenerator) buildOperation( if inputDesc != nil { if methodName != consts.HttpMethodGet && methodName != consts.HttpMethodHead && methodName != consts.HttpMethodDelete { + var additionalProperties []*openapi.NamedMediaType + bodySchema := g.getSchemaByOption(inputDesc, consts.ApiBody) - formSchema := g.getSchemaByOption(inputDesc, consts.ApiForm) - rawBodySchema := g.getSchemaByOption(inputDesc, consts.ApiRawBody) - var additionalProperties []*openapi.NamedMediaType if len(bodySchema.Properties.AdditionalProperties) > 0 { + bodyRefSchema := &openapi.NamedSchemaOrReference{ + Name: inputDesc.GetName() + consts.ComponentSchemaSuffixBody, + Value: &openapi.SchemaOrReference{Schema: bodySchema}, + } + + bodyRef := consts.ComponentSchemaPrefix + inputDesc.GetName() + consts.ComponentSchemaSuffixBody + + g.addSchemaToDocument(d, bodyRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeJSON, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Schema: bodySchema, + Reference: &openapi.Reference{Xref: bodyRef}, }, }, }) } + formSchema := g.getSchemaByOption(inputDesc, consts.ApiForm) + if len(formSchema.Properties.AdditionalProperties) > 0 { + formRefSchema := &openapi.NamedSchemaOrReference{ + Name: inputDesc.GetName() + consts.ComponentSchemaSuffixForm, + Value: &openapi.SchemaOrReference{Schema: formSchema}, + } + + formRef := consts.ComponentSchemaPrefix + inputDesc.GetName() + consts.ComponentSchemaSuffixForm + + g.addSchemaToDocument(d, formRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeFormMultipart, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Schema: formSchema, + Reference: &openapi.Reference{Xref: formRef}, }, }, }) @@ -472,18 +491,29 @@ func (g *OpenAPIGenerator) buildOperation( Name: consts.ContentTypeFormURLEncoded, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Schema: formSchema, + Reference: &openapi.Reference{Xref: formRef}, }, }, }) } + rawBodySchema := g.getSchemaByOption(inputDesc, consts.ApiRawBody) + if len(rawBodySchema.Properties.AdditionalProperties) > 0 { + rawBodyRefSchema := &openapi.NamedSchemaOrReference{ + Name: inputDesc.GetName() + consts.ComponentSchemaSuffixRawBody, + Value: &openapi.SchemaOrReference{Schema: rawBodySchema}, + } + + rawBodyRef := consts.ComponentSchemaPrefix + inputDesc.GetName() + consts.ComponentSchemaSuffixRawBody + + g.addSchemaToDocument(d, rawBodyRefSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeRawBody, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Schema: rawBodySchema, + Reference: &openapi.Reference{Xref: rawBodyRef}, }, }, }) diff --git a/thrift-gen-rpc-swagger/example/swagger/openapi.yaml b/thrift-gen-rpc-swagger/example/swagger/openapi.yaml index 27b9db5..22ecea8 100644 --- a/thrift-gen-rpc-swagger/example/swagger/openapi.yaml +++ b/thrift-gen-rpc-swagger/example/swagger/openapi.yaml @@ -25,14 +25,7 @@ paths: content: application/json: schema: - type: object - properties: - BodyValue: - type: string - description: 'field: body描述' - QueryValue: - type: string - description: 'field: query描述' + $ref: '#/components/schemas/BodyReq' responses: "200": description: HelloResp @@ -56,11 +49,7 @@ paths: content: application/json: schema: - type: object - properties: - PathValue: - type: string - description: 'field: path描述' + $ref: '#/components/schemas/PathReq' responses: "200": description: HelloResp @@ -78,24 +67,13 @@ paths: in: query description: metainfo for request schema: - type: object + type: object requestBody: description: QueryReq content: application/json: schema: - type: object - properties: - QueryValue: - title: Name - maxLength: 50 - minLength: 1 - type: string - description: Name - Items: - type: array - items: - type: string + $ref: '#/components/schemas/QueryReq' responses: "200": description: HelloResp @@ -105,6 +83,15 @@ paths: $ref: '#/components/schemas/HelloResp' components: schemas: + BodyReq: + type: object + properties: + BodyValue: + type: string + description: 'field: body描述' + QueryValue: + type: string + description: 'field: query描述' HelloResp: title: Hello - response required: @@ -122,6 +109,25 @@ components: type: string description: token description: Hello - response + PathReq: + type: object + properties: + PathValue: + type: string + description: 'field: path描述' + QueryReq: + type: object + properties: + QueryValue: + title: Name + maxLength: 50 + minLength: 1 + type: string + description: Name + Items: + type: array + items: + type: string tags: - name: HelloService1 description: HelloService1描述 diff --git a/thrift-gen-rpc-swagger/example/swagger/swagger.go b/thrift-gen-rpc-swagger/example/swagger/swagger.go index 92a7ecb..ed1463f 100644 --- a/thrift-gen-rpc-swagger/example/swagger/swagger.go +++ b/thrift-gen-rpc-swagger/example/swagger/swagger.go @@ -15,25 +15,36 @@ */ // Code generated by thrift-gen-rpc-swagger. -package main +package swagger import ( "context" _ "embed" "encoding/json" "errors" + "fmt" + "net" "net/http" "os" "path/filepath" + "regexp" "strings" "github.com/bytedance/gopkg/cloud/metainfo" "github.com/cloudwego/hertz/pkg/app" "github.com/cloudwego/hertz/pkg/app/server" "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/cloudwego/hertz/pkg/network" + "github.com/cloudwego/hertz/pkg/route" "github.com/cloudwego/kitex/client" "github.com/cloudwego/kitex/client/genericclient" + "github.com/cloudwego/kitex/pkg/endpoint" "github.com/cloudwego/kitex/pkg/generic" + "github.com/cloudwego/kitex/pkg/klog" + "github.com/cloudwego/kitex/pkg/remote" + "github.com/cloudwego/kitex/pkg/remote/trans/detection" + "github.com/cloudwego/kitex/pkg/remote/trans/netpoll" + "github.com/cloudwego/kitex/pkg/remote/trans/nphttp2" "github.com/cloudwego/kitex/pkg/transmeta" "github.com/cloudwego/kitex/transport" "github.com/hertz-contrib/cors" @@ -41,21 +52,82 @@ import ( swaggerFiles "github.com/swaggo/files" ) -//go:embed openapi.yaml -var openapiYAML []byte +var ( + //go:embed openapi.yaml + openapiYAML []byte + hertzEngine *route.Engine + httpReg = regexp.MustCompile("^(?:GET |POST|PUT|DELE|HEAD|OPTI|CONN|TRAC|PATC)$") +) + +const ( + kitexAddr = "127.0.0.1:8888" + idlFile = "hello.thrift" +) + +type MixTransHandlerFactory struct { + OriginFactory remote.ServerTransHandlerFactory +} + +type transHandler struct { + remote.ServerTransHandler +} + +func (t *transHandler) SetInvokeHandleFunc(inkHdlFunc endpoint.Endpoint) { + t.ServerTransHandler.(remote.InvokeHandleFuncSetter).SetInvokeHandleFunc(inkHdlFunc) +} + +func (m MixTransHandlerFactory) NewTransHandler(opt *remote.ServerOption) (remote.ServerTransHandler, error) { + + if hertzEngine == nil { + StartServer() + } + + var kitexOrigin remote.ServerTransHandler + var err error + + if m.OriginFactory != nil { + kitexOrigin, err = m.OriginFactory.NewTransHandler(opt) + } else { + kitexOrigin, err = detection.NewSvrTransHandlerFactory(netpoll.NewSvrTransHandlerFactory(), nphttp2.NewSvrTransHandlerFactory()).NewTransHandler(opt) + } + if err != nil { + return nil, err + } + return &transHandler{ServerTransHandler: kitexOrigin}, nil +} + +func (t *transHandler) OnRead(ctx context.Context, conn net.Conn) error { + c, ok := conn.(network.Conn) + if ok { + pre, _ := c.Peek(4) + if httpReg.Match(pre) { + klog.Info("using Hertz to process request") + err := hertzEngine.Serve(ctx, c) + if err != nil { + err = errors.New(fmt.Sprintf("HERTZ: %s", err.Error())) + } + return err + } + } -func main() { - h := server.Default(server.WithHostPorts("127.0.0.1:8080")) + return t.ServerTransHandler.OnRead(ctx, conn) +} +func StartServer() { + h := server.Default() h.Use(cors.Default()) cli := initializeGenericClient() setupSwaggerRoutes(h) setupProxyRoutes(h, cli) - hlog.Info("Swagger UI is available at: http://127.0.0.1:8080/swagger/index.html") + hlog.Info("Swagger UI is available at: http://" + kitexAddr + "/swagger/index.html") + err := h.Engine.Init() + if err != nil { + panic(err) + } - h.Spin() + hertzEngine = h.Engine } func findThriftFile(fileName string) (string, error) { @@ -65,13 +137,23 @@ func findThriftFile(fileName string) (string, error) { } foundPath := "" + relativePath := fileName + err = filepath.Walk(workingDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } - if !info.IsDir() && info.Name() == fileName { - foundPath = path - return filepath.SkipDir + + if !info.IsDir() { + relative, err := filepath.Rel(workingDir, path) + if err != nil { + return err + } + + if relative == relativePath { + foundPath = path + return filepath.SkipDir + } } return nil }) @@ -94,12 +176,12 @@ func findThriftFile(fileName string) (string, error) { } func initializeGenericClient() genericclient.Client { - thriftFile, err := findThriftFile("hello.thrift") + thriftFile, err := findThriftFile(idlFile) if err != nil { hlog.Fatal("Failed to locate Thrift file:", err) } - p, err := generic.NewThriftFileProvider(thriftFile) + p, err := generic.NewThriftFileProviderWithDynamicGo(thriftFile) if err != nil { hlog.Fatal("Failed to create ThriftFileProvider:", err) } @@ -111,7 +193,7 @@ func initializeGenericClient() genericclient.Client { var opts []client.Option opts = append(opts, client.WithTransportProtocol(transport.TTHeader)) opts = append(opts, client.WithMetaHandler(transmeta.ClientTTHeaderHandler)) - opts = append(opts, client.WithHostPorts("127.0.0.1:8888")) + opts = append(opts, client.WithHostPorts(kitexAddr)) cli, err := genericclient.NewClient("swagger", g, opts...) if err != nil { hlog.Fatal("Failed to create generic client:", err) @@ -187,11 +269,12 @@ func setupProxyRoutes(h *server.Hertz, cli genericclient.Client) { } ctx.Data(http.StatusOK, "application/json", respBody) + }) } func formatQueryParams(ctx *app.RequestContext) map[string]string { - QueryParams := make(map[string]string) + var QueryParams = make(map[string]string) ctx.Request.URI().QueryArgs().VisitAll(func(key, value []byte) { QueryParams[string(key)] = string(value) }) diff --git a/thrift-gen-rpc-swagger/generator/openapi_gen.go b/thrift-gen-rpc-swagger/generator/openapi_gen.go index 1d8e1cd..5022778 100644 --- a/thrift-gen-rpc-swagger/generator/openapi_gen.go +++ b/thrift-gen-rpc-swagger/generator/openapi_gen.go @@ -330,11 +330,20 @@ func (g *OpenAPIGenerator) buildOperation( var additionalProperties []*openapi.NamedMediaType if len(bodySchema.Properties.AdditionalProperties) > 0 { + refSchema := &openapi.NamedSchemaOrReference{ + Name: inputDesc.GetName(), + Value: &openapi.SchemaOrReference{Schema: bodySchema}, + } + + ref := consts.ComponentSchemaPrefix + inputDesc.GetName() + + g.addSchemaToDocument(d, refSchema) + additionalProperties = append(additionalProperties, &openapi.NamedMediaType{ Name: consts.ContentTypeJSON, Value: &openapi.MediaType{ Schema: &openapi.SchemaOrReference{ - Schema: bodySchema, + Reference: &openapi.Reference{Xref: ref}, }, }, })