service.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package swagger_api
  2. import (
  3. "context"
  4. "fmt"
  5. "git.ikuban.com/server/gnostic/protoc-gen-openapi/generator"
  6. "github.com/go-kratos/kratos/v2/api/metadata"
  7. "github.com/xmkuban/utils/utils"
  8. "google.golang.org/protobuf/compiler/protogen"
  9. "google.golang.org/protobuf/types/descriptorpb"
  10. "google.golang.org/protobuf/types/pluginpb"
  11. )
  12. // Service is service
  13. type Service struct {
  14. ser *Server
  15. }
  16. // New service
  17. func New(skipError bool) *Service {
  18. return &Service{
  19. ser: NewServer(nil, skipError),
  20. }
  21. }
  22. // ListServices list services
  23. func (s *Service) ListServices(ctx context.Context, in *metadata.ListServicesRequest) (*metadata.ListServicesReply, error) {
  24. return s.ser.ListServices(ctx, &metadata.ListServicesRequest{})
  25. }
  26. // GetServiceOpenAPI get service open api
  27. func (s *Service) GetServiceOpenAPI(ctx context.Context, in *metadata.GetServiceDescRequest) (string, error) {
  28. protoSet, err := s.ser.GetServiceDesc(ctx, in)
  29. if err != nil {
  30. return "", err
  31. }
  32. files := protoSet.FileDescSet.File
  33. newFiles := make([]*descriptorpb.FileDescriptorProto, 0)
  34. newFileMap := make(map[string]byte)
  35. for _, v := range files {
  36. if _, ok := newFileMap[v.GetName()]; !ok {
  37. newFiles = append(newFiles, v)
  38. newFileMap[v.GetName()] = 1
  39. }
  40. }
  41. files = newFiles
  42. var target string
  43. if len(files) == 0 {
  44. return "", fmt.Errorf("proto file is empty")
  45. }
  46. if files[len(files)-1].Name == nil {
  47. return "", fmt.Errorf("proto file's name is null")
  48. }
  49. target = files[len(files)-1].GetName()
  50. req := new(pluginpb.CodeGeneratorRequest)
  51. req.FileToGenerate = []string{target}
  52. var para = ""
  53. req.Parameter = &para
  54. req.ProtoFile = files
  55. opts := protogen.Options{}
  56. plugin, err := opts.New(req)
  57. if err != nil {
  58. return "", err
  59. }
  60. plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
  61. var content []byte
  62. gen := generator.NewOpenAPIv3Generator(plugin, generator.Configuration{
  63. Version: utils.ToPointString("1.0"),
  64. Title: utils.ToPointString(""),
  65. Description: utils.ToPointString(""),
  66. Naming: utils.ToPointString("json"),
  67. FQSchemaNaming: utils.ToPointBool(true),
  68. EnumType: utils.ToPointString("integer"),
  69. CircularDepth: utils.ToPointInt(2),
  70. DefaultResponse: utils.ToPointBool(false),
  71. OutputMode: utils.ToPointString("merged"),
  72. }, plugin.Files)
  73. content, err = gen.RunV2()
  74. if err != nil {
  75. return "", err
  76. }
  77. return string(content), nil
  78. }