utils.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. /*
  35. The paramter move function (mv)
  36. You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
  37. r (HTTP Request Object)
  38. getParamter (string, aka $_GET['This string])
  39. Will return
  40. Paramter string (if any)
  41. Error (if error)
  42. */
  43. /*
  44. func Mv(r *http.Request, getParamter string, postMode bool) (string, error) {
  45. if postMode == false {
  46. //Access the paramter via GET
  47. keys, ok := r.URL.Query()[getParamter]
  48. if !ok || len(keys[0]) < 1 {
  49. //log.Println("Url Param " + getParamter +" is missing")
  50. return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
  51. }
  52. // Query()["key"] will return an array of items,
  53. // we only want the single item.
  54. key := keys[0]
  55. return string(key), nil
  56. } else {
  57. //Access the parameter via POST
  58. r.ParseForm()
  59. x := r.Form.Get(getParamter)
  60. if len(x) == 0 || x == "" {
  61. return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
  62. }
  63. return string(x), nil
  64. }
  65. }
  66. */
  67. // Get GET parameter
  68. func GetPara(r *http.Request, key string) (string, error) {
  69. keys, ok := r.URL.Query()[key]
  70. if !ok || len(keys[0]) < 1 {
  71. return "", errors.New("invalid " + key + " given")
  72. } else {
  73. return keys[0], nil
  74. }
  75. }
  76. // Get POST paramter
  77. func PostPara(r *http.Request, key string) (string, error) {
  78. r.ParseForm()
  79. x := r.Form.Get(key)
  80. if x == "" {
  81. return "", errors.New("invalid " + key + " given")
  82. } else {
  83. return x, nil
  84. }
  85. }
  86. func FileExists(filename string) bool {
  87. _, err := os.Stat(filename)
  88. if os.IsNotExist(err) {
  89. return false
  90. }
  91. return true
  92. }
  93. func IsDir(path string) bool {
  94. if FileExists(path) == false {
  95. return false
  96. }
  97. fi, err := os.Stat(path)
  98. if err != nil {
  99. log.Fatal(err)
  100. return false
  101. }
  102. switch mode := fi.Mode(); {
  103. case mode.IsDir():
  104. return true
  105. case mode.IsRegular():
  106. return false
  107. }
  108. return false
  109. }
  110. func TimeToString(targetTime time.Time) string {
  111. return targetTime.Format("2006-01-02 15:04:05")
  112. }
  113. func LoadImageAsBase64(filepath string) (string, error) {
  114. if !FileExists(filepath) {
  115. return "", errors.New("File not exists")
  116. }
  117. f, _ := os.Open(filepath)
  118. reader := bufio.NewReader(f)
  119. content, _ := io.ReadAll(reader)
  120. encoded := base64.StdEncoding.EncodeToString(content)
  121. return string(encoded), nil
  122. }
  123. // Use for redirections
  124. func ConstructRelativePathFromRequestURL(requestURI string, redirectionLocation string) string {
  125. if strings.Count(requestURI, "/") == 1 {
  126. //Already root level
  127. return redirectionLocation
  128. }
  129. for i := 0; i < strings.Count(requestURI, "/")-1; i++ {
  130. redirectionLocation = "../" + redirectionLocation
  131. }
  132. return redirectionLocation
  133. }
  134. // Check if given string in a given slice
  135. func StringInArray(arr []string, str string) bool {
  136. for _, a := range arr {
  137. if a == str {
  138. return true
  139. }
  140. }
  141. return false
  142. }
  143. func StringInArrayIgnoreCase(arr []string, str string) bool {
  144. smallArray := []string{}
  145. for _, item := range arr {
  146. smallArray = append(smallArray, strings.ToLower(item))
  147. }
  148. return StringInArray(smallArray, strings.ToLower(str))
  149. }