utils.go 4.9 KB

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