helpers.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 := strings.TrimSuffix(strings.TrimPrefix(m, "<script>"), "</script>")
  130. s = mScriptCommentsInline.ReplaceAllString(s, "")
  131. s = mScriptCommentsMultiline.ReplaceAllString(s, "")
  132. s = mScriptLine.ReplaceAllString(s, "")
  133. s = mScriptEqual.ReplaceAllString(s, "=")
  134. s = mScriptDots.ReplaceAllString(s, ":\"")
  135. s = mScriptFuncs.ReplaceAllString(s, "){")
  136. return `<script>` + s + `</script>`
  137. })
  138. str = mHtml.ReplaceAllString(str, "><")
  139. str = mHtmlLeft.ReplaceAllString(str, ">")
  140. str = mHtmlRight.ReplaceAllString(str, "<")
  141. return str
  142. }
  143. func RespondAsBadRequest(w http.ResponseWriter, r *http.Request, err error) {
  144. if err != nil {
  145. log.Printf("%s\n", err.Error())
  146. w.Header().Set("Content-Type", "application/json")
  147. w.WriteHeader(http.StatusBadRequest)
  148. type Resp struct {
  149. Error string `json:"error"`
  150. }
  151. resp := Resp{
  152. Error: err.Error(),
  153. }
  154. j, err := json.Marshal(resp)
  155. if err != nil {
  156. log.Printf("%s\n", err.Error())
  157. return
  158. }
  159. if _, err := w.Write(j); err != nil {
  160. log.Printf("%s\n", err.Error())
  161. }
  162. } else {
  163. w.WriteHeader(http.StatusBadRequest)
  164. }
  165. }
  166. func RespondAsInternalServerError(w http.ResponseWriter, r *http.Request) {
  167. w.WriteHeader(http.StatusInternalServerError)
  168. }
  169. func RespondAsMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  170. w.WriteHeader(http.StatusMethodNotAllowed)
  171. }
  172. // Example:
  173. //
  174. // sess, err := helpers.SessionStart(w, r)
  175. //
  176. // if err != nil && !errors.Is(err, os.ErrNotExist) {
  177. //
  178. // helpers.RespondAsBadRequest(w, r, err)
  179. // return
  180. //
  181. // }
  182. //
  183. // defer sess.Close()
  184. func SessionStart(w http.ResponseWriter, r *http.Request) (*session.Session, error) {
  185. sess, err := session.New(w, r, "/tmp")
  186. if err != nil && !errors.Is(err, os.ErrNotExist) {
  187. log.Printf("%s\n", err.Error())
  188. }
  189. return sess, err
  190. }
  191. // Example:
  192. //
  193. // if err = r.ParseForm(); err != nil {
  194. // helpers.RespondAsBadRequest(w, r, err)
  195. // return
  196. // }
  197. //
  198. // if err = helpers.SetLanguageCookie(w, r); err != nil {
  199. // helpers.RespondAsBadRequest(w, r, err)
  200. // return
  201. // }
  202. func SetLanguageCookie(w http.ResponseWriter, r *http.Request) error {
  203. var clang string
  204. if c, err := r.Cookie("lang"); err == nil {
  205. clang = c.Value
  206. }
  207. lang := r.FormValue("lang")
  208. if lang != "" && lang != clang {
  209. http.SetCookie(w, &http.Cookie{
  210. Expires: time.Now().Add(365 * 24 * time.Hour),
  211. HttpOnly: true,
  212. Name: "lang",
  213. Path: "/",
  214. Value: lang,
  215. })
  216. }
  217. return nil
  218. }
  219. // -----------------------------------------------------------------------------
  220. // For funcs which write some data to http.ResponseWriter
  221. //
  222. // Example: w = NewFakeResponseWriter()
  223. //
  224. // w.Body, w.Headers, w.StatusCode
  225. type FakeResponseWriter struct {
  226. Body []byte
  227. Headers http.Header
  228. StatusCode int
  229. }
  230. func (w *FakeResponseWriter) Header() http.Header {
  231. return w.Headers
  232. }
  233. func (w *FakeResponseWriter) Write(b []byte) (int, error) {
  234. w.Body = append(w.Body, b...)
  235. return len(b), nil
  236. }
  237. func (w *FakeResponseWriter) WriteHeader(statusCode int) {
  238. w.StatusCode = statusCode
  239. }
  240. // Create fake http.ResponseWriter for using in tests
  241. func NewFakeResponseWriter() *FakeResponseWriter {
  242. return &FakeResponseWriter{
  243. Body: []byte{},
  244. Headers: http.Header{},
  245. StatusCode: http.StatusOK,
  246. }
  247. }