wrapper.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package wrapper
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "os"
  9. "time"
  10. "golang-fave/consts"
  11. "golang-fave/engine/mysqlpool"
  12. "golang-fave/engine/sqlw"
  13. "golang-fave/logger"
  14. "golang-fave/utils"
  15. "github.com/vladimirok5959/golang-server-sessions/session"
  16. )
  17. type Tx = sqlw.Tx
  18. var ErrNoRows = sqlw.ErrNoRows
  19. type Wrapper struct {
  20. l *logger.Logger
  21. W http.ResponseWriter
  22. R *http.Request
  23. S *session.Session
  24. Host string
  25. Port string
  26. CurrHost string
  27. DConfig string
  28. DHtdocs string
  29. DLogs string
  30. DTemplate string
  31. DTmp string
  32. IsBackend bool
  33. ConfMysqlExists bool
  34. UrlArgs []string
  35. CurrModule string
  36. CurrSubModule string
  37. MSPool *mysqlpool.MySqlPool
  38. DB *sqlw.DB
  39. User *utils.MySql_user
  40. }
  41. func New(l *logger.Logger, w http.ResponseWriter, r *http.Request, s *session.Session, host, port, chost, dirConfig, dirHtdocs, dirLogs, dirTemplate, dirTmp string, mp *mysqlpool.MySqlPool) *Wrapper {
  42. return &Wrapper{
  43. l: l,
  44. W: w,
  45. R: r,
  46. S: s,
  47. Host: host,
  48. Port: port,
  49. CurrHost: chost,
  50. DConfig: dirConfig,
  51. DHtdocs: dirHtdocs,
  52. DLogs: dirLogs,
  53. DTemplate: dirTemplate,
  54. DTmp: dirTmp,
  55. UrlArgs: []string{},
  56. CurrModule: "",
  57. CurrSubModule: "",
  58. MSPool: mp,
  59. }
  60. }
  61. func (this *Wrapper) LogAccess(msg string, vars ...interface{}) {
  62. this.l.Log(msg, this.R, false, vars...)
  63. }
  64. func (this *Wrapper) LogError(msg string, vars ...interface{}) {
  65. this.l.Log(msg, this.R, true, vars...)
  66. }
  67. func (this *Wrapper) dbReconnect() error {
  68. if !utils.IsMySqlConfigExists(this.DConfig + string(os.PathSeparator) + "mysql.json") {
  69. return errors.New("can't read database configuration file")
  70. }
  71. mc, err := utils.MySqlConfigRead(this.DConfig + string(os.PathSeparator) + "mysql.json")
  72. if err != nil {
  73. return err
  74. }
  75. this.DB, err = sqlw.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
  76. if err != nil {
  77. return err
  78. }
  79. this.MSPool.Set(this.CurrHost, this.DB)
  80. return nil
  81. }
  82. func (this *Wrapper) UseDatabase() error {
  83. this.DB = this.MSPool.Get(this.CurrHost)
  84. if this.DB == nil {
  85. if err := this.dbReconnect(); err != nil {
  86. return err
  87. }
  88. }
  89. if err := this.DB.Ping(); err != nil {
  90. this.DB.Close()
  91. if err := this.dbReconnect(); err != nil {
  92. return err
  93. }
  94. if err := this.DB.Ping(); err != nil {
  95. this.DB.Close()
  96. return err
  97. }
  98. }
  99. // Max 30 minutes and max 2 connection per host
  100. this.DB.SetConnMaxLifetime(time.Minute * 30)
  101. this.DB.SetMaxIdleConns(2)
  102. this.DB.SetMaxOpenConns(2)
  103. return nil
  104. }
  105. func (this *Wrapper) LoadSessionUser() bool {
  106. if this.S.GetInt("UserId", 0) <= 0 {
  107. return false
  108. }
  109. if this.DB == nil {
  110. return false
  111. }
  112. user := &utils.MySql_user{}
  113. err := this.DB.QueryRow(`
  114. SELECT
  115. id,
  116. first_name,
  117. last_name,
  118. email,
  119. password,
  120. admin,
  121. active
  122. FROM
  123. users
  124. WHERE
  125. id = ?
  126. LIMIT 1;`,
  127. this.S.GetInt("UserId", 0),
  128. ).Scan(
  129. &user.A_id,
  130. &user.A_first_name,
  131. &user.A_last_name,
  132. &user.A_email,
  133. &user.A_password,
  134. &user.A_admin,
  135. &user.A_active,
  136. )
  137. if err != nil {
  138. return false
  139. }
  140. if user.A_id != this.S.GetInt("UserId", 0) {
  141. return false
  142. }
  143. this.User = user
  144. return true
  145. }
  146. func (this *Wrapper) Write(data string) {
  147. this.W.Write([]byte(data))
  148. }
  149. func (this *Wrapper) MsgSuccess(msg string) {
  150. this.Write(fmt.Sprintf(
  151. `fave.ShowMsgSuccess('Success!', '%s', false);`,
  152. utils.JavaScriptVarValue(msg)))
  153. }
  154. func (this *Wrapper) MsgError(msg string) {
  155. this.Write(fmt.Sprintf(
  156. `fave.ShowMsgError('Error!', '%s', true);`,
  157. utils.JavaScriptVarValue(msg)))
  158. }
  159. func (this *Wrapper) RenderToString(tcont []byte, data interface{}) string {
  160. tmpl, err := template.New("template").Parse(string(tcont))
  161. if err != nil {
  162. return err.Error()
  163. }
  164. var tpl bytes.Buffer
  165. if err := tmpl.Execute(&tpl, data); err != nil {
  166. return err.Error()
  167. }
  168. return tpl.String()
  169. }
  170. func (this *Wrapper) RenderFrontEnd(tname string, data interface{}, status int) {
  171. tmpl, err := template.ParseFiles(
  172. this.DTemplate+string(os.PathSeparator)+tname+".html",
  173. this.DTemplate+string(os.PathSeparator)+"header.html",
  174. this.DTemplate+string(os.PathSeparator)+"sidebar-left.html",
  175. this.DTemplate+string(os.PathSeparator)+"sidebar-right.html",
  176. this.DTemplate+string(os.PathSeparator)+"footer.html",
  177. )
  178. if err != nil {
  179. utils.SystemErrorPageTemplate(this.W, err)
  180. return
  181. }
  182. this.W.WriteHeader(status)
  183. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  184. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  185. var tpl bytes.Buffer
  186. err = tmpl.Execute(&tpl, consts.TmplData{
  187. System: utils.GetTmplSystemData(),
  188. Data: data,
  189. })
  190. if err != nil {
  191. utils.SystemErrorPageTemplate(this.W, err)
  192. return
  193. }
  194. this.W.Write(tpl.Bytes())
  195. }
  196. func (this *Wrapper) RenderBackEnd(tcont []byte, data interface{}) {
  197. tmpl, err := template.New("template").Parse(string(tcont))
  198. if err != nil {
  199. utils.SystemErrorPageEngine(this.W, err)
  200. return
  201. }
  202. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  203. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  204. var tpl bytes.Buffer
  205. err = tmpl.Execute(this.W, consts.TmplData{
  206. System: utils.GetTmplSystemData(),
  207. Data: data,
  208. })
  209. if err != nil {
  210. utils.SystemErrorPageEngine(this.W, err)
  211. return
  212. }
  213. this.W.Write(tpl.Bytes())
  214. }