helpers.go 4.6 KB

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