helpers.go 4.4 KB

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