client.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. case ServiceTypeActivity:
  26. baseURL = DefaultActivityBaseURL
  27. case ServiceTypePlan:
  28. baseURL = DefaultPlanBaseURL
  29. default:
  30. baseURL = DefaultPersonBaseURL
  31. }
  32. }
  33. httpClient := resty.New().
  34. SetBaseURL(baseURL).
  35. SetTimeout(time.Duration(timeout)*time.Second).
  36. SetHeader("Content-Type", "application/json")
  37. c := &Client{
  38. config: &config,
  39. http: httpClient,
  40. }
  41. c.manage = &ManageService{client: c}
  42. c.opLog = &OperateLogService{client: c}
  43. return c
  44. }
  45. func (c *Client) Type() ServiceType {
  46. return c.config.Type
  47. }
  48. func (c *Client) Manage() *ManageService {
  49. return c.manage
  50. }
  51. func (c *Client) OperateLog() *OperateLogService {
  52. return c.opLog
  53. }
  54. func (c *Client) Version() (map[string]any, error) {
  55. var resp VersionResponse
  56. _, err := c.http.R().SetResult(&resp).Get("/version")
  57. if err != nil {
  58. return nil, fmt.Errorf("请求版本接口失败: %w", err)
  59. }
  60. if !resp.Success {
  61. return nil, fmt.Errorf("获取版本失败: %s", resp.Msg)
  62. }
  63. return resp.Data, nil
  64. }
  65. func (c *Client) apiV1Path(path string) string {
  66. return fmt.Sprintf("/v1%s", path)
  67. }