utils.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package hds
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "net"
  7. "net/http"
  8. "strconv"
  9. "sync"
  10. "time"
  11. )
  12. func isJSON(s string) bool {
  13. var js map[string]interface{}
  14. return json.Unmarshal([]byte(s), &js) == nil
  15. }
  16. func tryGet(url string) (string, error) {
  17. client := http.Client{
  18. Timeout: 5 * time.Second,
  19. }
  20. resp, err := client.Get(url)
  21. if err != nil {
  22. return "", err
  23. }
  24. if resp.StatusCode != 200 {
  25. return "", errors.New("Server side return status code " + strconv.Itoa(resp.StatusCode))
  26. }
  27. content, err := ioutil.ReadAll(resp.Body)
  28. if err != nil {
  29. return "", err
  30. }
  31. return string(content), nil
  32. }
  33. //Check if the given ip address is HDS device, return its UUID if true
  34. func tryGetHDSUUID(wg *sync.WaitGroup, ip string) (string, error) {
  35. defer wg.Done()
  36. uuid, err := tryGet("http://" + ip + "/uuid")
  37. if err != nil {
  38. return "", err
  39. }
  40. return uuid, nil
  41. }
  42. func getLocalIP() string {
  43. addrs, err := net.InterfaceAddrs()
  44. if err != nil {
  45. return ""
  46. }
  47. for _, address := range addrs {
  48. // check the address type and if it is not a loopback the display it
  49. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  50. if ipnet.IP.To4() != nil {
  51. return ipnet.IP.String()
  52. }
  53. }
  54. }
  55. return ""
  56. }