wrapper.go 4.8 KB

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