utils.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. func GetBool(r *http.Request, key string) (bool, error) {
  45. x, err := GetPara(r, key)
  46. if err != nil {
  47. return false, err
  48. }
  49. x = strings.TrimSpace(x)
  50. if x == "1" || strings.ToLower(x) == "true" {
  51. return true, nil
  52. } else if x == "0" || strings.ToLower(x) == "false" {
  53. return false, nil
  54. }
  55. return false, errors.New("invalid boolean given")
  56. }
  57. // Get GET paramter as int
  58. func GetInt(r *http.Request, key string) (int, error) {
  59. x, err := GetPara(r, key)
  60. if err != nil {
  61. return 0, err
  62. }
  63. x = strings.TrimSpace(x)
  64. rx, err := strconv.Atoi(x)
  65. if err != nil {
  66. return 0, err
  67. }
  68. return rx, nil
  69. }
  70. // Get POST paramter
  71. func PostPara(r *http.Request, key string) (string, error) {
  72. r.ParseForm()
  73. x := r.Form.Get(key)
  74. if x == "" {
  75. return "", errors.New("invalid " + key + " given")
  76. } else {
  77. return x, nil
  78. }
  79. }
  80. func PostBool(r *http.Request, key string) (bool, error) {
  81. x, err := PostPara(r, key)
  82. if err != nil {
  83. return false, err
  84. }
  85. x = strings.TrimSpace(x)
  86. if x == "1" || strings.ToLower(x) == "true" {
  87. return true, nil
  88. } else if x == "0" || strings.ToLower(x) == "false" {
  89. return false, nil
  90. }
  91. return false, errors.New("invalid boolean given")
  92. }
  93. // Get POST paramter as int
  94. func PostInt(r *http.Request, key string) (int, error) {
  95. x, err := PostPara(r, key)
  96. if err != nil {
  97. return 0, err
  98. }
  99. x = strings.TrimSpace(x)
  100. rx, err := strconv.Atoi(x)
  101. if err != nil {
  102. return 0, err
  103. }
  104. return rx, nil
  105. }
  106. func FileExists(filename string) bool {
  107. _, err := os.Stat(filename)
  108. if os.IsNotExist(err) {
  109. return false
  110. }
  111. return true
  112. }
  113. func IsDir(path string) bool {
  114. if FileExists(path) == false {
  115. return false
  116. }
  117. fi, err := os.Stat(path)
  118. if err != nil {
  119. log.Fatal(err)
  120. return false
  121. }
  122. switch mode := fi.Mode(); {
  123. case mode.IsDir():
  124. return true
  125. case mode.IsRegular():
  126. return false
  127. }
  128. return false
  129. }
  130. func TimeToString(targetTime time.Time) string {
  131. return targetTime.Format("2006-01-02 15:04:05")
  132. }
  133. func LoadImageAsBase64(filepath string) (string, error) {
  134. if !FileExists(filepath) {
  135. return "", errors.New("File not exists")
  136. }
  137. f, _ := os.Open(filepath)
  138. reader := bufio.NewReader(f)
  139. content, _ := io.ReadAll(reader)
  140. encoded := base64.StdEncoding.EncodeToString(content)
  141. return string(encoded), nil
  142. }
  143. // Use for redirections
  144. func ConstructRelativePathFromRequestURL(requestURI string, redirectionLocation string) string {
  145. if strings.Count(requestURI, "/") == 1 {
  146. //Already root level
  147. return redirectionLocation
  148. }
  149. for i := 0; i < strings.Count(requestURI, "/")-1; i++ {
  150. redirectionLocation = "../" + redirectionLocation
  151. }
  152. return redirectionLocation
  153. }
  154. // Check if given string in a given slice
  155. func StringInArray(arr []string, str string) bool {
  156. for _, a := range arr {
  157. if a == str {
  158. return true
  159. }
  160. }
  161. return false
  162. }
  163. func StringInArrayIgnoreCase(arr []string, str string) bool {
  164. smallArray := []string{}
  165. for _, item := range arr {
  166. smallArray = append(smallArray, strings.ToLower(item))
  167. }
  168. return StringInArray(smallArray, strings.ToLower(str))
  169. }
  170. // Load template and replace keys within
  171. func Templateload(templateFile string, data map[string]string) (string, error) {
  172. content, err := os.ReadFile(templateFile)
  173. if err != nil {
  174. return "", err
  175. }
  176. for key, value := range data {
  177. key = "{{" + key + "}}"
  178. content = []byte(strings.ReplaceAll(string(content), key, value))
  179. }
  180. return string(content), nil
  181. }
  182. // Apply template from a pre-loaded string
  183. func TemplateApply(templateString string, data map[string]string) string {
  184. content := []byte(templateString)
  185. for key, value := range data {
  186. key = "{{" + key + "}}"
  187. content = []byte(strings.ReplaceAll(string(content), key, value))
  188. }
  189. return string(content)
  190. }
  191. func FilenameIsWebSafe(filename string) bool {
  192. unsafeChars := []string{"/", "\\", "?", "%", "*", ":", "|", "\"", "<", ">"}
  193. for _, char := range unsafeChars {
  194. if strings.Contains(filename, char) {
  195. return false
  196. }
  197. }
  198. return true
  199. }