helpers.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package helpers
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "regexp"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/vladimirok5959/golang-server-sessions/session"
  14. )
  15. // func ClientIP(r *http.Request) string
  16. // func ClientIPs(r *http.Request) []string
  17. // func HandleAppStatus() http.Handler
  18. // func HandleFile(data, contentType string) http.Handler
  19. // func HandleImagePng(data string) http.Handler
  20. // func HandleTextJavaScript(data string) http.Handler
  21. // func HandleTextPlain(data string) http.Handler
  22. // func HandleTextXml(data string) http.Handler
  23. // func MinifyHtmlCode(str string) string
  24. // func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error)
  25. // func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request)
  26. // func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error)
  27. // func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error
  28. var mHtml = regexp.MustCompile(`>[\n\t\r]+<`)
  29. var mHtmlLeft = regexp.MustCompile(`>[\n\t\r]+`)
  30. var mHtmlRight = regexp.MustCompile(`[\n\t\r]+<`)
  31. func ClientIP(r *http.Request) string {
  32. ips := ClientIPs(r)
  33. if len(ips) >= 1 {
  34. return ips[0]
  35. }
  36. return ""
  37. }
  38. func ClientIPs(r *http.Request) []string {
  39. ra := r.RemoteAddr
  40. if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), " "); xff != "" {
  41. ra = strings.Join([]string{xff, ra}, ",")
  42. }
  43. res := []string{}
  44. ips := strings.Split(ra, ",")
  45. for _, ip := range ips {
  46. res = append(res, strings.Trim(ip, " "))
  47. }
  48. return res
  49. }
  50. func HandleAppStatus() http.Handler {
  51. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  52. if r.Method != http.MethodGet {
  53. RespondAsMethodNotAllowed(w, r)
  54. return
  55. }
  56. var m runtime.MemStats
  57. runtime.ReadMemStats(&m)
  58. memory := fmt.Sprintf(
  59. `{"alloc":"%v","total_alloc":"%v","sys":"%v","num_gc":"%v"}`,
  60. m.Alloc, m.TotalAlloc, m.Sys, m.NumGC,
  61. )
  62. w.Header().Set("Content-Type", "application/json")
  63. if _, err := w.Write([]byte(fmt.Sprintf(`{"routines":%d,"memory":%s}`, runtime.NumGoroutine(), memory))); err != nil {
  64. log.Printf("%s\n", err.Error())
  65. }
  66. })
  67. }
  68. func HandleFile(data, contentType string) http.Handler {
  69. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  70. if r.Method != http.MethodGet {
  71. RespondAsMethodNotAllowed(w, r)
  72. return
  73. }
  74. w.Header().Set("Content-Type", contentType)
  75. if _, err := w.Write([]byte(data)); err != nil {
  76. fmt.Printf("%s\n", err.Error())
  77. }
  78. })
  79. }
  80. func HandleImagePng(data string) http.Handler {
  81. return HandleFile(data, "image/png")
  82. }
  83. func HandleTextJavaScript(data string) http.Handler {
  84. return HandleFile(data, "text/javascript")
  85. }
  86. func HandleTextPlain(data string) http.Handler {
  87. return HandleFile(data, "text/plain")
  88. }
  89. func HandleTextXml(data string) http.Handler {
  90. return HandleFile(data, "text/xml")
  91. }
  92. func MinifyHtmlCode(str string) string {
  93. str = mHtml.ReplaceAllString(str, "><")
  94. str = mHtmlLeft.ReplaceAllString(str, ">")
  95. str = mHtmlRight.ReplaceAllString(str, "<")
  96. return str
  97. }
  98. func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error) {
  99. if err != nil {
  100. log.Printf("%s\n", err.Error())
  101. w.Header().Set("Content-Type", "application/json")
  102. w.WriteHeader(http.StatusBadRequest)
  103. if _, e := w.Write([]byte(`{"error":` + strconv.Quote(err.Error()) + `}`)); e != nil {
  104. log.Printf("%s\n", e.Error())
  105. }
  106. } else {
  107. w.WriteHeader(http.StatusBadRequest)
  108. }
  109. }
  110. func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  111. w.WriteHeader(http.StatusMethodNotAllowed)
  112. }
  113. // Example:
  114. //
  115. // sess, err := helpers.SessionStart(w, r)
  116. //
  117. // if err != nil && !errors.Is(err, os.ErrNotExist) {
  118. //
  119. // helpers.RespondAsBadRequest(w, r, err)
  120. // return
  121. //
  122. // }
  123. //
  124. // defer sess.Close()
  125. func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error) {
  126. sess, err := session.New(w, r, "/tmp")
  127. if err != nil && !errors.Is(err, os.ErrNotExist) {
  128. log.Printf("%s\n", err.Error())
  129. }
  130. return sess, err
  131. }
  132. // Example:
  133. //
  134. // if err = r.ParseForm(); err != nil {
  135. // helpers.RespondAsBadRequest(w, r, err)
  136. // return
  137. // }
  138. //
  139. // if err = helpers.SetLanguageCookie(w, r); err != nil {
  140. // helpers.RespondAsBadRequest(w, r, err)
  141. // return
  142. // }
  143. func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error {
  144. var clang string
  145. if c, err := r.Cookie("lang"); err == nil {
  146. clang = c.Value
  147. }
  148. lang := r.Form.Get("lang")
  149. if lang != "" && lang != clang {
  150. http.SetCookie(w, &http.Cookie{
  151. Name: "lang",
  152. Value: lang,
  153. Expires: time.Now().Add(365 * 24 * time.Hour),
  154. HttpOnly: true,
  155. })
  156. }
  157. return nil
  158. }