instance.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sdk
  2. import (
  3. "git.sxidc.com/service-supports/ds-sdk/client"
  4. "git.sxidc.com/service-supports/ds-sdk/grpc_client"
  5. "github.com/pkg/errors"
  6. )
  7. var sdkInstance *SDK
  8. func GetInstance() *SDK {
  9. return sdkInstance
  10. }
  11. func InitInstance(token string, address string, httpPort string, grpcPort string, namespace string, dataSource string, opts ...Option) error {
  12. if sdkInstance != nil {
  13. return nil
  14. }
  15. options := &Options{
  16. token: token,
  17. baseUrl: "http://" + address + ":" + httpPort,
  18. grpcAddress: address + ":" + grpcPort,
  19. namespace: namespace,
  20. dataSource: dataSource,
  21. }
  22. for _, opt := range opts {
  23. opt(options)
  24. }
  25. c := client.New(options.timeout)
  26. namespaceInfos, err := c.GetNamespaces(options.token, options.baseUrl, options.namespace, 1, 1)
  27. if err != nil {
  28. return err
  29. }
  30. if namespaceInfos == nil || len(namespaceInfos) == 0 {
  31. return errors.New("命名空间不存在")
  32. }
  33. dataSourceInfos, err := c.GetDataSources(
  34. options.token, options.baseUrl, options.namespace, options.dataSource, "", 1, 1)
  35. if err != nil {
  36. return err
  37. }
  38. if dataSourceInfos == nil || len(dataSourceInfos) == 0 {
  39. return errors.New("数据源不存在")
  40. }
  41. grpcClient, err := grpc_client.NewClient(options.grpcAddress)
  42. if err != nil {
  43. return err
  44. }
  45. sdkInstance = &SDK{
  46. options: options,
  47. client: c,
  48. grpcClient: grpcClient,
  49. }
  50. return nil
  51. }
  52. func DestroyInstance() error {
  53. if sdkInstance == nil {
  54. return nil
  55. }
  56. err := grpc_client.Destroy(sdkInstance.grpcClient)
  57. if err != nil {
  58. return err
  59. }
  60. sdkInstance = nil
  61. return nil
  62. }