utils.go 3.5 KB

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