utils.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package hds
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "log"
  7. "net"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. func isJSON(s string) bool {
  14. var js map[string]interface{}
  15. return json.Unmarshal([]byte(s), &js) == nil
  16. }
  17. func tryGet(url string) (string, error) {
  18. client := http.Client{
  19. Timeout: 10 * time.Second,
  20. }
  21. resp, err := client.Get(url)
  22. if err != nil {
  23. return "", err
  24. }
  25. if resp.StatusCode != 200 {
  26. return "", errors.New("Server side return status code " + strconv.Itoa(resp.StatusCode))
  27. }
  28. content, err := ioutil.ReadAll(resp.Body)
  29. if err != nil {
  30. return "", err
  31. }
  32. return string(content), nil
  33. }
  34. //Check if the given ip address is HDS device, return its UUID if true
  35. func tryGetHDSUUID(ip string) (string, error) {
  36. uuid, err := tryGet("http://" + ip + "/uuid")
  37. if err != nil {
  38. return "", err
  39. }
  40. log.Println(ip, uuid)
  41. return uuid, nil
  42. }
  43. //Get the HDS device info, return Device Name, Class and error if any
  44. func tryGetHDSInfo(ip string) (string, string, error) {
  45. infoStatus, err := tryGet("http://" + ip + "/info")
  46. if err != nil {
  47. return "", "", err
  48. }
  49. infodata := strings.Split(infoStatus, "_")
  50. if len(infodata) != 2 {
  51. return "", "", errors.New("Invalid HDS info string")
  52. }
  53. return infodata[0], infodata[1], nil
  54. }
  55. //Get the HDS device status. Only use this when you are sure the device is an HDS device
  56. func getHDSStatus(ip string) (string, error) {
  57. status, err := tryGet("http://" + ip + "/status")
  58. if err != nil {
  59. return "", err
  60. }
  61. return status, nil
  62. }
  63. func getLocalIP() string {
  64. addrs, err := net.InterfaceAddrs()
  65. if err != nil {
  66. return ""
  67. }
  68. for _, address := range addrs {
  69. // check the address type and if it is not a loopback the display it
  70. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  71. if ipnet.IP.To4() != nil {
  72. return ipnet.IP.String()
  73. }
  74. }
  75. }
  76. return ""
  77. }