helpers.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package helpers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "net/http"
  7. "os"
  8. "regexp"
  9. "runtime"
  10. "strings"
  11. "time"
  12. "github.com/vladimirok5959/golang-server-sessions/session"
  13. )
  14. // func ClientIP(r *http.Request) string
  15. // func ClientIPs(r *http.Request) []string
  16. // func HandleAppStatus() http.Handler
  17. // func HandleFile(data, contentType string) http.Handler
  18. // func HandleImageJpeg(data 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 RespondAsInternalServerError(w http.ResponseWriter, r *http.Request)
  27. // func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request)
  28. // func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error)
  29. // func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error
  30. var mHtml = regexp.MustCompile(`>[\n\t\r]+<`)
  31. var mHtmlLeft = regexp.MustCompile(`>[\n\t\r]+`)
  32. var mHtmlRight = regexp.MustCompile(`[\n\t\r]+<`)
  33. func ClientIP(r *http.Request) string {
  34. ips := ClientIPs(r)
  35. if len(ips) >= 1 {
  36. return ips[0]
  37. }
  38. return ""
  39. }
  40. func ClientIPs(r *http.Request) []string {
  41. ra := r.RemoteAddr
  42. if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), " "); xff != "" {
  43. ra = strings.Join([]string{xff, ra}, ",")
  44. }
  45. res := []string{}
  46. ips := strings.Split(ra, ",")
  47. for _, ip := range ips {
  48. res = append(res, strings.Trim(ip, " "))
  49. }
  50. return res
  51. }
  52. func HandleAppStatus() http.Handler {
  53. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  54. if r.Method != http.MethodGet {
  55. RespondAsMethodNotAllowed(w, r)
  56. return
  57. }
  58. var m runtime.MemStats
  59. runtime.ReadMemStats(&m)
  60. type respMemory struct {
  61. Alloc uint64 `json:"alloc"`
  62. NumGC uint32 `json:"num_gc"`
  63. Sys uint64 `json:"sys"`
  64. TotalAlloc uint64 `json:"total_alloc"`
  65. }
  66. type respRoot struct {
  67. Memory respMemory `json:"memory"`
  68. Routines int `json:"routines"`
  69. }
  70. resp := respRoot{
  71. Memory: respMemory{
  72. Alloc: m.Alloc,
  73. NumGC: m.NumGC,
  74. Sys: m.Sys,
  75. TotalAlloc: m.TotalAlloc,
  76. },
  77. Routines: runtime.NumGoroutine(),
  78. }
  79. j, err := json.Marshal(resp)
  80. if err != nil {
  81. RespondAsBadRequest(w, r, err)
  82. return
  83. }
  84. w.Header().Set("Content-Type", "application/json")
  85. if _, err := w.Write(j); err != nil {
  86. log.Printf("%s\n", err.Error())
  87. }
  88. })
  89. }
  90. func HandleFile(data, contentType string) http.Handler {
  91. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. if r.Method != http.MethodGet {
  93. RespondAsMethodNotAllowed(w, r)
  94. return
  95. }
  96. w.Header().Set("Content-Type", contentType)
  97. if _, err := w.Write([]byte(data)); err != nil {
  98. log.Printf("%s\n", err.Error())
  99. }
  100. })
  101. }
  102. func HandleImageJpeg(data string) http.Handler {
  103. return HandleFile(data, "image/jpeg")
  104. }
  105. func HandleImagePng(data string) http.Handler {
  106. return HandleFile(data, "image/png")
  107. }
  108. func HandleTextCss(data string) http.Handler {
  109. return HandleFile(data, "text/css")
  110. }
  111. func HandleTextJavaScript(data string) http.Handler {
  112. return HandleFile(data, "text/javascript")
  113. }
  114. func HandleTextPlain(data string) http.Handler {
  115. return HandleFile(data, "text/plain")
  116. }
  117. func HandleTextXml(data string) http.Handler {
  118. return HandleFile(data, "text/xml")
  119. }
  120. func MinifyHtmlCode(str string) string {
  121. str = mHtml.ReplaceAllString(str, "><")
  122. str = mHtmlLeft.ReplaceAllString(str, ">")
  123. str = mHtmlRight.ReplaceAllString(str, "<")
  124. return str
  125. }
  126. func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error) {
  127. if err != nil {
  128. log.Printf("%s\n", err.Error())
  129. w.Header().Set("Content-Type", "application/json")
  130. w.WriteHeader(http.StatusBadRequest)
  131. type respRoot struct {
  132. Error string `json:"error"`
  133. }
  134. resp := respRoot{
  135. Error: err.Error(),
  136. }
  137. j, err := json.Marshal(resp)
  138. if err != nil {
  139. log.Printf("%s\n", err.Error())
  140. return
  141. }
  142. if _, err := w.Write(j); err != nil {
  143. log.Printf("%s\n", err.Error())
  144. }
  145. } else {
  146. w.WriteHeader(http.StatusBadRequest)
  147. }
  148. }
  149. func RespondAsInternalServerError(w http.ResponseWriter, r *http.Request) {
  150. w.WriteHeader(http.StatusInternalServerError)
  151. }
  152. func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  153. w.WriteHeader(http.StatusMethodNotAllowed)
  154. }
  155. // Example:
  156. //
  157. // sess, err := helpers.SessionStart(w, r)
  158. //
  159. // if err != nil && !errors.Is(err, os.ErrNotExist) {
  160. //
  161. // helpers.RespondAsBadRequest(w, r, err)
  162. // return
  163. //
  164. // }
  165. //
  166. // defer sess.Close()
  167. func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error) {
  168. sess, err := session.New(w, r, "/tmp")
  169. if err != nil && !errors.Is(err, os.ErrNotExist) {
  170. log.Printf("%s\n", err.Error())
  171. }
  172. return sess, err
  173. }
  174. // Example:
  175. //
  176. // if err = r.ParseForm(); err != nil {
  177. // helpers.RespondAsBadRequest(w, r, err)
  178. // return
  179. // }
  180. //
  181. // if err = helpers.SetLanguageCookie(w, r); err != nil {
  182. // helpers.RespondAsBadRequest(w, r, err)
  183. // return
  184. // }
  185. func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error {
  186. var clang string
  187. if c, err := r.Cookie("lang"); err == nil {
  188. clang = c.Value
  189. }
  190. lang := r.Form.Get("lang")
  191. if lang != "" && lang != clang {
  192. http.SetCookie(w, &http.Cookie{
  193. Name: "lang",
  194. Value: lang,
  195. Expires: time.Now().Add(365 * 24 * time.Hour),
  196. HttpOnly: true,
  197. })
  198. }
  199. return nil
  200. }