client.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package managesdk
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/go-resty/resty/v2"
  6. )
  7. type Client struct {
  8. config *Config
  9. http *resty.Client
  10. manage *ManageService
  11. opLog *OperateLogService
  12. }
  13. func NewClient(config Config) *Client {
  14. timeout := 10
  15. if config.Timeout > 0 {
  16. timeout = config.Timeout
  17. }
  18. baseURL := config.BaseURL
  19. if baseURL == "" {
  20. switch config.Type {
  21. case ServiceTypePerson:
  22. baseURL = DefaultPersonBaseURL
  23. case ServiceTypeResource:
  24. baseURL = DefaultResourceBaseURL
  25. default:
  26. baseURL = DefaultPersonBaseURL
  27. }
  28. }
  29. httpClient := resty.New().
  30. SetBaseURL(baseURL).
  31. SetTimeout(time.Duration(timeout)*time.Second).
  32. SetHeader("Content-Type", "application/json")
  33. c := &Client{
  34. config: &config,
  35. http: httpClient,
  36. }
  37. c.manage = &ManageService{client: c}
  38. c.opLog = &OperateLogService{client: c}
  39. return c
  40. }
  41. func (c *Client) Type() ServiceType {
  42. return c.config.Type
  43. }
  44. func (c *Client) Manage() *ManageService {
  45. return c.manage
  46. }
  47. func (c *Client) OperateLog() *OperateLogService {
  48. return c.opLog
  49. }
  50. func (c *Client) Version() (map[string]any, error) {
  51. var resp VersionResponse
  52. _, err := c.http.R().SetResult(&resp).Get("/version")
  53. if err != nil {
  54. return nil, fmt.Errorf("请求版本接口失败: %w", err)
  55. }
  56. if !resp.Success {
  57. return nil, fmt.Errorf("获取版本失败: %s", resp.Msg)
  58. }
  59. return resp.Data, nil
  60. }
  61. func (c *Client) apiV1Path(path string) string {
  62. return fmt.Sprintf("/v1%s", path)
  63. }