helpers.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "time"
  10. )
  11. func parseDate(layout,datetime string) time.Time {
  12. t, err := time.Parse(layout, datetime)
  13. if err != nil {
  14. log.Println(err)
  15. }
  16. return t
  17. }
  18. func parseDateToString(layout,datetime,format string) string {
  19. return parseDate(layout, datetime).Format(format)
  20. }
  21. func parseDateToUnix(layout,datetime string) int64 {
  22. return parseDate(layout, datetime).Unix()
  23. }
  24. func runBash(script string) string {
  25. if *debug {
  26. log.Println(script)
  27. }
  28. cmd := exec.Command("bash", "-c", script)
  29. stdout, err := cmd.CombinedOutput()
  30. if err != nil {
  31. return (fmt.Sprint(err) + " : " + string(stdout))
  32. }
  33. return string(stdout)
  34. }
  35. func fExist(path string) bool {
  36. var _, err = os.Stat(path)
  37. if os.IsNotExist(err) {
  38. return false
  39. } else if err != nil {
  40. log.Fatal(err)
  41. return false
  42. }
  43. return true
  44. }
  45. func fRead(path string) string {
  46. content, err := ioutil.ReadFile(path)
  47. if err != nil {
  48. log.Fatal(err)
  49. }
  50. return string(content)
  51. }
  52. func fCreate(path string) bool {
  53. var _, err = os.Stat(path)
  54. if os.IsNotExist(err) {
  55. var file, err = os.Create(path)
  56. if err != nil {
  57. log.Println(err)
  58. return false
  59. }
  60. defer file.Close()
  61. }
  62. return true
  63. }
  64. func fWrite(path, content string) {
  65. err := ioutil.WriteFile(path, []byte(content), 0644)
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. }
  70. func fDelete(path string) {
  71. err := os.Remove(path)
  72. if err != nil {
  73. log.Fatal(err)
  74. }
  75. }
  76. func fDownload(path, url string, basicAuth bool) error {
  77. client := &http.Client{}
  78. req, err := http.NewRequest("GET", url, nil)
  79. if basicAuth {
  80. req.SetBasicAuth(*masterBasicAuthUser, *masterBasicAuthPassword)
  81. }
  82. resp, err := client.Do(req)
  83. if err != nil {
  84. return err
  85. }
  86. if resp.StatusCode != 200 {
  87. log.Printf("WARNING: Download file operation for url %s finished with status code %d\n", url, resp.StatusCode )
  88. }
  89. defer resp.Body.Close()
  90. body, err := ioutil.ReadAll(resp.Body)
  91. if err != nil {
  92. return err
  93. }
  94. fCreate(path)
  95. fWrite(path, string(body))
  96. return nil
  97. }