helpers.go 7.1 KB

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