helpers.go 8.3 KB

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