common.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/base64"
  5. "errors"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. /*
  15. SYSTEM COMMON FUNCTIONS
  16. This is a system function that put those we usually use function but not belongs to
  17. any module / system.
  18. E.g. fileExists / IsDir etc
  19. */
  20. /*
  21. Basic Response Functions
  22. Send response with ease
  23. */
  24. //Send text response with given w and message as string
  25. func sendTextResponse(w http.ResponseWriter, msg string) {
  26. w.Write([]byte(msg))
  27. }
  28. //Send JSON response, with an extra json header
  29. func sendJSONResponse(w http.ResponseWriter, json string) {
  30. w.Header().Set("Content-Type", "application/json")
  31. w.Write([]byte(json))
  32. }
  33. func sendErrorResponse(w http.ResponseWriter, errMsg string) {
  34. w.Header().Set("Content-Type", "application/json")
  35. w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
  36. }
  37. func sendOK(w http.ResponseWriter) {
  38. w.Header().Set("Content-Type", "application/json")
  39. w.Write([]byte("\"OK\""))
  40. }
  41. /*
  42. The paramter move function (mv)
  43. You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
  44. r (HTTP Request Object)
  45. getParamter (string, aka $_GET['This string])
  46. Will return
  47. Paramter string (if any)
  48. Error (if error)
  49. */
  50. func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
  51. if postMode == false {
  52. //Access the paramter via GET
  53. keys, ok := r.URL.Query()[getParamter]
  54. if !ok || len(keys[0]) < 1 {
  55. //log.Println("Url Param " + getParamter +" is missing")
  56. return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
  57. }
  58. // Query()["key"] will return an array of items,
  59. // we only want the single item.
  60. key := keys[0]
  61. return string(key), nil
  62. } else {
  63. //Access the parameter via POST
  64. r.ParseForm()
  65. x := r.Form.Get(getParamter)
  66. if len(x) == 0 || x == "" {
  67. return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
  68. }
  69. return string(x), nil
  70. }
  71. }
  72. func stringInSlice(a string, list []string) bool {
  73. for _, b := range list {
  74. if b == a {
  75. return true
  76. }
  77. }
  78. return false
  79. }
  80. func fileExists(filename string) bool {
  81. _, err := os.Stat(filename)
  82. if os.IsNotExist(err) {
  83. return false
  84. } else if err != nil {
  85. //Some edge case for Input Output error can occur here.
  86. //Return false if that is the case
  87. return false
  88. }
  89. return true
  90. }
  91. func IsDir(path string) bool {
  92. if fileExists(path) == false {
  93. return false
  94. }
  95. fi, err := os.Stat(path)
  96. if err != nil {
  97. log.Fatal(err)
  98. return false
  99. }
  100. switch mode := fi.Mode(); {
  101. case mode.IsDir():
  102. return true
  103. case mode.IsRegular():
  104. return false
  105. }
  106. return false
  107. }
  108. func inArray(arr []string, str string) bool {
  109. for _, a := range arr {
  110. if a == str {
  111. return true
  112. }
  113. }
  114. return false
  115. }
  116. func timeToString(targetTime time.Time) string {
  117. return targetTime.Format("2006-01-02 15:04:05")
  118. }
  119. func IntToString(number int) string {
  120. return strconv.Itoa(number)
  121. }
  122. func StringToInt(number string) (int, error) {
  123. return strconv.Atoi(number)
  124. }
  125. func StringToInt64(number string) (int64, error) {
  126. i, err := strconv.ParseInt(number, 10, 64)
  127. if err != nil {
  128. return -1, err
  129. }
  130. return i, nil
  131. }
  132. func Int64ToString(number int64) string {
  133. convedNumber := strconv.FormatInt(number, 10)
  134. return convedNumber
  135. }
  136. func GetUnixTime() int64 {
  137. return time.Now().Unix()
  138. }
  139. func LoadImageAsBase64(filepath string) (string, error) {
  140. if !fileExists(filepath) {
  141. return "", errors.New("File not exists")
  142. }
  143. f, _ := os.Open(filepath)
  144. reader := bufio.NewReader(f)
  145. content, _ := ioutil.ReadAll(reader)
  146. encoded := base64.StdEncoding.EncodeToString(content)
  147. return string(encoded), nil
  148. }
  149. func PushToSliceIfNotExist(slice []string, newItem string) []string {
  150. itemExists := false
  151. for _, item := range slice {
  152. if item == newItem {
  153. itemExists = true
  154. }
  155. }
  156. if !itemExists {
  157. slice = append(slice, newItem)
  158. }
  159. return slice
  160. }
  161. func RemoveFromSliceIfExists(slice []string, target string) []string {
  162. newSlice := []string{}
  163. for _, item := range slice {
  164. if item != target {
  165. newSlice = append(newSlice, item)
  166. }
  167. }
  168. return newSlice
  169. }
  170. //Get the IP address of the current authentication user
  171. func ReflectUserIP(w http.ResponseWriter, r *http.Request) {
  172. requestPort, _ := mv(r, "port", false)
  173. showPort := false
  174. if requestPort == "true" {
  175. //Show port as well
  176. showPort = true
  177. }
  178. IPAddress := r.Header.Get("X-Real-Ip")
  179. if IPAddress == "" {
  180. IPAddress = r.Header.Get("X-Forwarded-For")
  181. }
  182. if IPAddress == "" {
  183. IPAddress = r.RemoteAddr
  184. }
  185. if !showPort {
  186. IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
  187. }
  188. w.Write([]byte(IPAddress))
  189. return
  190. }