common.go 4.3 KB

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