common.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. Basic Response Functions
  16. Send response with ease
  17. */
  18. //Send text response with given w and message as string
  19. func sendTextResponse(w http.ResponseWriter, msg string) {
  20. w.Write([]byte(msg))
  21. }
  22. //Send JSON response, with an extra json header
  23. func sendJSONResponse(w http.ResponseWriter, json string) {
  24. w.Header().Set("Content-Type", "application/json")
  25. w.Write([]byte(json))
  26. }
  27. func sendErrorResponse(w http.ResponseWriter, errMsg string) {
  28. w.Header().Set("Content-Type", "application/json")
  29. w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
  30. }
  31. func sendOK(w http.ResponseWriter) {
  32. w.Header().Set("Content-Type", "application/json")
  33. w.Write([]byte("\"OK\""))
  34. }
  35. /*
  36. The paramter move function (mv)
  37. You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
  38. r (HTTP Request Object)
  39. getParamter (string, aka $_GET['This string])
  40. Will return
  41. Paramter string (if any)
  42. Error (if error)
  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. func stringInSlice(a string, list []string) bool {
  67. for _, b := range list {
  68. if b == a {
  69. return true
  70. }
  71. }
  72. return false
  73. }
  74. func fileExists(filename string) bool {
  75. _, err := os.Stat(filename)
  76. if os.IsNotExist(err) {
  77. return false
  78. }
  79. return true
  80. }
  81. func IsDir(path string) bool {
  82. if fileExists(path) == false {
  83. return false
  84. }
  85. fi, err := os.Stat(path)
  86. if err != nil {
  87. log.Fatal(err)
  88. return false
  89. }
  90. switch mode := fi.Mode(); {
  91. case mode.IsDir():
  92. return true
  93. case mode.IsRegular():
  94. return false
  95. }
  96. return false
  97. }
  98. func inArray(arr []string, str string) bool {
  99. for _, a := range arr {
  100. if a == str {
  101. return true
  102. }
  103. }
  104. return false
  105. }
  106. func timeToString(targetTime time.Time) string {
  107. return targetTime.Format("2006-01-02 15:04:05")
  108. }
  109. func IntToString(number int) string {
  110. return strconv.Itoa(number)
  111. }
  112. func StringToInt(number string) (int, error) {
  113. return strconv.Atoi(number)
  114. }
  115. func StringToInt64(number string) (int64, error) {
  116. i, err := strconv.ParseInt(number, 10, 64)
  117. if err != nil {
  118. return -1, err
  119. }
  120. return i, nil
  121. }
  122. func Int64ToString(number int64) string {
  123. convedNumber := strconv.FormatInt(number, 10)
  124. return convedNumber
  125. }
  126. func GetUnixTime() int64 {
  127. return time.Now().Unix()
  128. }
  129. func LoadImageAsBase64(filepath string) (string, error) {
  130. if !fileExists(filepath) {
  131. return "", errors.New("File not exists")
  132. }
  133. f, _ := os.Open(filepath)
  134. reader := bufio.NewReader(f)
  135. content, _ := ioutil.ReadAll(reader)
  136. encoded := base64.StdEncoding.EncodeToString(content)
  137. return string(encoded), nil
  138. }
  139. //Get the IP address of the current authentication user
  140. func getUserIPAddr(w http.ResponseWriter, r *http.Request) {
  141. requestPort, _ := mv(r, "port", false)
  142. showPort := false
  143. if requestPort == "true" {
  144. //Show port as well
  145. showPort = true
  146. }
  147. IPAddress := r.Header.Get("X-Real-Ip")
  148. if IPAddress == "" {
  149. IPAddress = r.Header.Get("X-Forwarded-For")
  150. }
  151. if IPAddress == "" {
  152. IPAddress = r.RemoteAddr
  153. }
  154. if !showPort {
  155. IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
  156. }
  157. w.Write([]byte(IPAddress))
  158. return
  159. }