common.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package main
  2. import (
  3. "os"
  4. "log"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "errors"
  9. "encoding/base64"
  10. "bufio"
  11. "io/ioutil"
  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. }
  85. return true
  86. }
  87. func IsDir(path string) bool{
  88. if (fileExists(path) == false){
  89. return false
  90. }
  91. fi, err := os.Stat(path)
  92. if err != nil {
  93. log.Fatal(err)
  94. return false
  95. }
  96. switch mode := fi.Mode(); {
  97. case mode.IsDir():
  98. return true
  99. case mode.IsRegular():
  100. return false
  101. }
  102. return false
  103. }
  104. func inArray(arr []string, str string) bool {
  105. for _, a := range arr {
  106. if a == str {
  107. return true
  108. }
  109. }
  110. return false
  111. }
  112. func timeToString(targetTime time.Time) string{
  113. return targetTime.Format("2006-01-02 15:04:05")
  114. }
  115. func IntToString(number int) string{
  116. return strconv.Itoa(number)
  117. }
  118. func StringToInt(number string) (int, error){
  119. return strconv.Atoi(number)
  120. }
  121. func StringToInt64(number string) (int64, error){
  122. i, err := strconv.ParseInt(number, 10, 64)
  123. if err != nil {
  124. return -1, err
  125. }
  126. return i, nil
  127. }
  128. func Int64ToString(number int64) string{
  129. convedNumber:=strconv.FormatInt(number,10)
  130. return convedNumber
  131. }
  132. func GetUnixTime() int64{
  133. return time.Now().Unix()
  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, _ := ioutil.ReadAll(reader)
  142. encoded := base64.StdEncoding.EncodeToString(content)
  143. return string(encoded), nil
  144. }
  145. func PushToSliceIfNotExist(slice []string, newItem string) []string {
  146. itemExists := false
  147. for _, item := range slice{
  148. if item == newItem{
  149. itemExists = true
  150. }
  151. }
  152. if !itemExists{
  153. slice = append(slice, newItem)
  154. }
  155. return slice
  156. }
  157. func RemoveFromSliceIfExists(slice []string, target string) []string {
  158. newSlice := []string{}
  159. for _, item := range slice{
  160. if item != target{
  161. newSlice = append(newSlice, item)
  162. }
  163. }
  164. return newSlice;
  165. }
  166. //Get the IP address of the current authentication user
  167. func ReflectUserIP(w http.ResponseWriter, r *http.Request) {
  168. requestPort,_ := mv(r, "port", false)
  169. showPort := false;
  170. if (requestPort == "true"){
  171. //Show port as well
  172. showPort = true;
  173. }
  174. IPAddress := r.Header.Get("X-Real-Ip")
  175. if IPAddress == "" {
  176. IPAddress = r.Header.Get("X-Forwarded-For")
  177. }
  178. if IPAddress == "" {
  179. IPAddress = r.RemoteAddr
  180. }
  181. if (!showPort){
  182. IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
  183. }
  184. w.Write([]byte(IPAddress))
  185. return;
  186. }