helpers.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. var mScript = regexp.MustCompile(`<script>([^<]*)</script>`)
  34. var mScriptLine = regexp.MustCompile(`[\n\t\r]+`)
  35. var mScriptEqual = regexp.MustCompile(`[\n\t\r\s]+=[\n\t\r\s]+`)
  36. var mScriptDots = regexp.MustCompile(`:[\n\t\r\s]+"`)
  37. func ClientIP(r *http.Request) string {
  38. ips := ClientIPs(r)
  39. if len(ips) >= 1 {
  40. return ips[0]
  41. }
  42. return ""
  43. }
  44. func ClientIPs(r *http.Request) []string {
  45. ra := r.RemoteAddr
  46. if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), " "); xff != "" {
  47. ra = strings.Join([]string{xff, ra}, ",")
  48. }
  49. res := []string{}
  50. ips := strings.Split(ra, ",")
  51. for _, ip := range ips {
  52. res = append(res, strings.Trim(ip, " "))
  53. }
  54. return res
  55. }
  56. func HandleAppStatus() http.Handler {
  57. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  58. if r.Method != http.MethodGet {
  59. RespondAsMethodNotAllowed(w, r)
  60. return
  61. }
  62. var m runtime.MemStats
  63. runtime.ReadMemStats(&m)
  64. type respMemory struct {
  65. Alloc uint64 `json:"alloc"`
  66. NumGC uint32 `json:"num_gc"`
  67. Sys uint64 `json:"sys"`
  68. TotalAlloc uint64 `json:"total_alloc"`
  69. }
  70. type respRoot struct {
  71. Memory respMemory `json:"memory"`
  72. Routines int `json:"routines"`
  73. }
  74. resp := respRoot{
  75. Memory: respMemory{
  76. Alloc: m.Alloc,
  77. NumGC: m.NumGC,
  78. Sys: m.Sys,
  79. TotalAlloc: m.TotalAlloc,
  80. },
  81. Routines: runtime.NumGoroutine(),
  82. }
  83. j, err := json.Marshal(resp)
  84. if err != nil {
  85. RespondAsBadRequest(w, r, err)
  86. return
  87. }
  88. w.Header().Set("Content-Type", "application/json")
  89. if _, err := w.Write(j); err != nil {
  90. log.Printf("%s\n", err.Error())
  91. }
  92. })
  93. }
  94. func HandleFile(data, contentType string) http.Handler {
  95. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  96. if r.Method != http.MethodGet {
  97. RespondAsMethodNotAllowed(w, r)
  98. return
  99. }
  100. w.Header().Set("Content-Type", contentType)
  101. if _, err := w.Write([]byte(data)); err != nil {
  102. log.Printf("%s\n", err.Error())
  103. }
  104. })
  105. }
  106. func HandleImageJpeg(data string) http.Handler {
  107. return HandleFile(data, "image/jpeg")
  108. }
  109. func HandleImagePng(data string) http.Handler {
  110. return HandleFile(data, "image/png")
  111. }
  112. func HandleTextCss(data string) http.Handler {
  113. return HandleFile(data, "text/css")
  114. }
  115. func HandleTextJavaScript(data string) http.Handler {
  116. return HandleFile(data, "text/javascript")
  117. }
  118. func HandleTextPlain(data string) http.Handler {
  119. return HandleFile(data, "text/plain")
  120. }
  121. func HandleTextXml(data string) http.Handler {
  122. return HandleFile(data, "text/xml")
  123. }
  124. func MinifyHtmlCode(str string) string {
  125. str = mScript.ReplaceAllStringFunc(str, func(m string) string {
  126. s := strings.TrimSuffix(strings.TrimPrefix(m, "<script>"), "</script>")
  127. s = mScriptLine.ReplaceAllString(s, "")
  128. s = mScriptEqual.ReplaceAllString(s, "=")
  129. s = mScriptDots.ReplaceAllString(s, ":\"")
  130. return `<script>` + s + `</script>`
  131. })
  132. str = mHtml.ReplaceAllString(str, "><")
  133. str = mHtmlLeft.ReplaceAllString(str, ">")
  134. str = mHtmlRight.ReplaceAllString(str, "<")
  135. return str
  136. }
  137. func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error) {
  138. if err != nil {
  139. log.Printf("%s\n", err.Error())
  140. w.Header().Set("Content-Type", "application/json")
  141. w.WriteHeader(http.StatusBadRequest)
  142. type Resp struct {
  143. Error string `json:"error"`
  144. }
  145. resp := Resp{
  146. Error: err.Error(),
  147. }
  148. j, err := json.Marshal(resp)
  149. if err != nil {
  150. log.Printf("%s\n", err.Error())
  151. return
  152. }
  153. if _, err := w.Write(j); err != nil {
  154. log.Printf("%s\n", err.Error())
  155. }
  156. } else {
  157. w.WriteHeader(http.StatusBadRequest)
  158. }
  159. }
  160. func RespondAsInternalServerError(w http.ResponseWriter, r *http.Request) {
  161. w.WriteHeader(http.StatusInternalServerError)
  162. }
  163. func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  164. w.WriteHeader(http.StatusMethodNotAllowed)
  165. }
  166. // Example:
  167. //
  168. // sess, err := helpers.SessionStart(w, r)
  169. //
  170. // if err != nil && !errors.Is(err, os.ErrNotExist) {
  171. //
  172. // helpers.RespondAsBadRequest(w, r, err)
  173. // return
  174. //
  175. // }
  176. //
  177. // defer sess.Close()
  178. func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error) {
  179. sess, err := session.New(w, r, "/tmp")
  180. if err != nil && !errors.Is(err, os.ErrNotExist) {
  181. log.Printf("%s\n", err.Error())
  182. }
  183. return sess, err
  184. }
  185. // Example:
  186. //
  187. // if err = r.ParseForm(); err != nil {
  188. // helpers.RespondAsBadRequest(w, r, err)
  189. // return
  190. // }
  191. //
  192. // if err = helpers.SetLanguageCookie(w, r); err != nil {
  193. // helpers.RespondAsBadRequest(w, r, err)
  194. // return
  195. // }
  196. func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error {
  197. var clang string
  198. if c, err := r.Cookie("lang"); err == nil {
  199. clang = c.Value
  200. }
  201. lang := r.FormValue("lang")
  202. if lang != "" && lang != clang {
  203. http.SetCookie(w, &http.Cookie{
  204. Expires: time.Now().Add(365 * 24 * time.Hour),
  205. HttpOnly: true,
  206. Name: "lang",
  207. Path: "/",
  208. Value: lang,
  209. })
  210. }
  211. return nil
  212. }
  213. // -----------------------------------------------------------------------------
  214. // For funcs which write some data to http.ResponseWriter
  215. //
  216. // Example: w = NewFakeResponseWriter()
  217. //
  218. // w.Body, w.Headers, w.StatusCode
  219. type FakeResponseWriter struct {
  220. Body []byte
  221. Headers http.Header
  222. StatusCode int
  223. }
  224. func (w *FakeResponseWriter) Header() http.Header {
  225. return w.Headers
  226. }
  227. func (w *FakeResponseWriter) Write(b []byte) (int, error) {
  228. w.Body = append(w.Body, b...)
  229. return len(b), nil
  230. }
  231. func (w *FakeResponseWriter) WriteHeader(statusCode int) {
  232. w.StatusCode = statusCode
  233. }
  234. // Create fake http.ResponseWriter for using in tests
  235. func NewFakeResponseWriter() *FakeResponseWriter {
  236. return &FakeResponseWriter{
  237. Body: []byte{},
  238. Headers: http.Header{},
  239. StatusCode: http.StatusOK,
  240. }
  241. }