utils.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package utils
  2. import (
  3. "bufio"
  4. "encoding/base64"
  5. "errors"
  6. "io"
  7. "log"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. /*
  15. Common
  16. Some commonly used functions in ArozOS
  17. */
  18. // Response related
  19. func SendTextResponse(w http.ResponseWriter, msg string) {
  20. w.Write([]byte(msg))
  21. }
  22. // Send JSON response, with an extra json header
  23. func SendJSONResponse(w http.ResponseWriter, json string) {
  24. w.Header().Set("Content-Type", "application/json")
  25. w.Write([]byte(json))
  26. }
  27. func SendErrorResponse(w http.ResponseWriter, errMsg string) {
  28. w.Header().Set("Content-Type", "application/json")
  29. w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
  30. }
  31. func SendOK(w http.ResponseWriter) {
  32. w.Header().Set("Content-Type", "application/json")
  33. w.Write([]byte("\"OK\""))
  34. }
  35. // Get GET parameter
  36. func GetPara(r *http.Request, key string) (string, error) {
  37. keys, ok := r.URL.Query()[key]
  38. if !ok || len(keys[0]) < 1 {
  39. return "", errors.New("invalid " + key + " given")
  40. } else {
  41. return keys[0], nil
  42. }
  43. }
  44. // Get POST paramter
  45. func PostPara(r *http.Request, key string) (string, error) {
  46. r.ParseForm()
  47. x := r.Form.Get(key)
  48. if x == "" {
  49. return "", errors.New("invalid " + key + " given")
  50. } else {
  51. return x, nil
  52. }
  53. }
  54. func PostBool(r *http.Request, key string) (bool, error) {
  55. x, err := PostPara(r, key)
  56. if err != nil {
  57. return false, err
  58. }
  59. x = strings.TrimSpace(x)
  60. if x == "1" || strings.ToLower(x) == "true" {
  61. return true, nil
  62. } else if x == "0" || strings.ToLower(x) == "false" {
  63. return false, nil
  64. }
  65. return false, errors.New("invalid boolean given")
  66. }
  67. // Get POST paramter as int
  68. func PostInt(r *http.Request, key string) (int, error) {
  69. x, err := PostPara(r, key)
  70. if err != nil {
  71. return 0, err
  72. }
  73. x = strings.TrimSpace(x)
  74. rx, err := strconv.Atoi(x)
  75. if err != nil {
  76. return 0, err
  77. }
  78. return rx, nil
  79. }
  80. func FileExists(filename string) bool {
  81. _, err := os.Stat(filename)
  82. if os.IsNotExist(err) {
  83. return false
  84. }
  85. return true
  86. }
  87. func IsDir(path string) bool {
  88. if FileExists(path) == false {
  89. return false
  90. }
  91. fi, err := os.Stat(path)
  92. if err != nil {
  93. log.Fatal(err)
  94. return false
  95. }
  96. switch mode := fi.Mode(); {
  97. case mode.IsDir():
  98. return true
  99. case mode.IsRegular():
  100. return false
  101. }
  102. return false
  103. }
  104. func TimeToString(targetTime time.Time) string {
  105. return targetTime.Format("2006-01-02 15:04:05")
  106. }
  107. func LoadImageAsBase64(filepath string) (string, error) {
  108. if !FileExists(filepath) {
  109. return "", errors.New("File not exists")
  110. }
  111. f, _ := os.Open(filepath)
  112. reader := bufio.NewReader(f)
  113. content, _ := io.ReadAll(reader)
  114. encoded := base64.StdEncoding.EncodeToString(content)
  115. return string(encoded), nil
  116. }
  117. // Use for redirections
  118. func ConstructRelativePathFromRequestURL(requestURI string, redirectionLocation string) string {
  119. if strings.Count(requestURI, "/") == 1 {
  120. //Already root level
  121. return redirectionLocation
  122. }
  123. for i := 0; i < strings.Count(requestURI, "/")-1; i++ {
  124. redirectionLocation = "../" + redirectionLocation
  125. }
  126. return redirectionLocation
  127. }
  128. // Check if given string in a given slice
  129. func StringInArray(arr []string, str string) bool {
  130. for _, a := range arr {
  131. if a == str {
  132. return true
  133. }
  134. }
  135. return false
  136. }
  137. func StringInArrayIgnoreCase(arr []string, str string) bool {
  138. smallArray := []string{}
  139. for _, item := range arr {
  140. smallArray = append(smallArray, strings.ToLower(item))
  141. }
  142. return StringInArray(smallArray, strings.ToLower(str))
  143. }
  144. // Load template and replace keys within
  145. func Templateload(templateFile string, data map[string]string) (string, error) {
  146. content, err := os.ReadFile(templateFile)
  147. if err != nil {
  148. return "", err
  149. }
  150. for key, value := range data {
  151. key = "{{" + key + "}}"
  152. content = []byte(strings.ReplaceAll(string(content), key, value))
  153. }
  154. return string(content), nil
  155. }
  156. // Apply template from a pre-loaded string
  157. func TemplateApply(templateString string, data map[string]string) string {
  158. content := []byte(templateString)
  159. for key, value := range data {
  160. key = "{{" + key + "}}"
  161. content = []byte(strings.ReplaceAll(string(content), key, value))
  162. }
  163. return string(content)
  164. }