helpers.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. fmt.Println(script)
  26. cmd := exec.Command("bash", "-c", script)
  27. stdout, err := cmd.CombinedOutput()
  28. if err != nil {
  29. return (fmt.Sprint(err) + " : " + string(stdout))
  30. }
  31. return string(stdout)
  32. }
  33. func fExist(path string) bool {
  34. var _, err = os.Stat(path)
  35. if os.IsNotExist(err) {
  36. return false
  37. } else if err != nil {
  38. log.Fatal(err)
  39. return false
  40. }
  41. return true
  42. }
  43. func fRead(path string) string {
  44. content, err := ioutil.ReadFile(path)
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. return string(content)
  49. }
  50. func fCreate(path string) bool {
  51. var _, err = os.Stat(path)
  52. if os.IsNotExist(err) {
  53. var file, err = os.Create(path)
  54. if err != nil {
  55. log.Println(err)
  56. return false
  57. }
  58. defer file.Close()
  59. }
  60. return true
  61. }
  62. func fWrite(path, content string) {
  63. err := ioutil.WriteFile(path, []byte(content), 0644)
  64. if err != nil {
  65. log.Fatal(err)
  66. }
  67. }
  68. func fDelete(path string) {
  69. err := os.Remove(path)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. }
  74. func fDownload(path, url string, basicAuth bool) error {
  75. client := &http.Client{}
  76. req, err := http.NewRequest("GET", url, nil)
  77. if basicAuth {
  78. req.SetBasicAuth(*masterBasicAuthUser, *masterBasicAuthPassword)
  79. }
  80. resp, err := client.Do(req)
  81. if err != nil {
  82. return err
  83. }
  84. if resp.StatusCode != 200 {
  85. log.Printf("WARNING: Download file operation for url %s finished with status code %d", url, resp.StatusCode )
  86. }
  87. defer resp.Body.Close()
  88. body, err := ioutil.ReadAll(resp.Body)
  89. if err != nil {
  90. return err
  91. }
  92. fCreate(path)
  93. fWrite(path, string(body))
  94. return nil
  95. }