safeline.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package service
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. )
  12. var cacheCount InstallerCount
  13. type InstallerCount struct {
  14. Total int `json:"total"`
  15. }
  16. type SafelineService struct {
  17. client *http.Client
  18. APIHost string
  19. }
  20. func NewSafelineService(host string) *SafelineService {
  21. return &SafelineService{
  22. APIHost: host,
  23. client: &http.Client{
  24. Transport: &http.Transport{
  25. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  26. },
  27. },
  28. }
  29. }
  30. func (s *SafelineService) GetInstallerCount(ctx context.Context) (InstallerCount, error) {
  31. req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.APIHost+"/api/v1/public/safeline/count", nil)
  32. if err != nil {
  33. return cacheCount, err
  34. }
  35. res, err := s.client.Do(req)
  36. if err != nil {
  37. return cacheCount, err
  38. }
  39. defer res.Body.Close()
  40. var r map[string]interface{}
  41. if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
  42. return cacheCount, err
  43. }
  44. if r["code"].(float64) != 0 {
  45. return cacheCount, nil
  46. }
  47. cacheCount = InstallerCount{
  48. Total: int(r["data"].(map[string]interface{})["total"].(float64)),
  49. }
  50. return cacheCount, nil
  51. }
  52. // GetExist return ip if id exist
  53. func (s *SafelineService) GetExist(ctx context.Context, id string, token string) (string, error) {
  54. body := fmt.Sprintf(`{"id":"%s", "token": "%s"}`, id, token)
  55. req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.APIHost+"/api/v1/public/safeline/exist", strings.NewReader(body))
  56. if err != nil {
  57. return "", err
  58. }
  59. res, err := s.client.Do(req)
  60. if err != nil {
  61. return "", err
  62. }
  63. defer res.Body.Close()
  64. if res.StatusCode != http.StatusOK {
  65. raw, _ := io.ReadAll(res.Body)
  66. return "", errors.New(string(raw))
  67. }
  68. var r map[string]interface{}
  69. if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
  70. return "", err
  71. }
  72. if r["code"].(float64) != 0 {
  73. return "", nil
  74. }
  75. return r["data"].(map[string]interface{})["ip"].(string), nil
  76. }