helpers.go 7.9 KB

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