wrapper.go 5.2 KB

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