helpers.go 7.3 KB

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