token.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package client
  2. import (
  3. "fmt"
  4. "net/url"
  5. "strconv"
  6. )
  7. const (
  8. generateTokenUrl = "/ds/api/admin/token/generate"
  9. deleteTokenUrl = "/ds/api/admin/token/delete"
  10. getTokensUrl = "/ds/api/admin/token/query"
  11. )
  12. func (c *Client) GenerateToken(token string, baseUrl string, name string) (string, error) {
  13. fullUrl, err := url.JoinPath(baseUrl, generateTokenUrl)
  14. if err != nil {
  15. return "", err
  16. }
  17. resp := new(struct {
  18. MsgResponse
  19. Token string `json:"token"`
  20. })
  21. err = c.post(token, fullUrl, map[string]any{
  22. "name": name,
  23. }, resp)
  24. if err != nil {
  25. return "", err
  26. }
  27. if !resp.Success {
  28. return "", fmt.Errorf(resp.Msg)
  29. }
  30. return resp.Token, nil
  31. }
  32. func (c *Client) DeleteToken(token string, baseUrl string, name string) error {
  33. fullUrl, err := url.JoinPath(baseUrl, deleteTokenUrl)
  34. if err != nil {
  35. return err
  36. }
  37. resp := new(MsgResponse)
  38. err = c.post(token, fullUrl, map[string]any{
  39. "name": name,
  40. }, resp)
  41. if err != nil {
  42. return err
  43. }
  44. if !resp.Success {
  45. return fmt.Errorf(resp.Msg)
  46. }
  47. return nil
  48. }
  49. func (c *Client) GetTokens(token string, baseUrl string, name string, pageNo int, pageSize int) ([]TokenInfo, error) {
  50. fullUrl, err := url.JoinPath(baseUrl, getTokensUrl)
  51. if err != nil {
  52. return nil, err
  53. }
  54. resp := new(InfosResponse[TokenInfo])
  55. err = c.get(token, fullUrl, map[string]string{
  56. "name": name,
  57. "pageNo": strconv.Itoa(pageNo),
  58. "pageSize": strconv.Itoa(pageSize),
  59. }, resp)
  60. if err != nil {
  61. return nil, err
  62. }
  63. if !resp.Success {
  64. return nil, fmt.Errorf(resp.Msg)
  65. }
  66. return resp.Infos, nil
  67. }