wrapper.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package wrapper
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "golang-fave/logger"
  10. "golang-fave/utils"
  11. _ "github.com/go-sql-driver/mysql"
  12. "github.com/vladimirok5959/golang-server-sessions/session"
  13. )
  14. type Wrapper struct {
  15. l *logger.Logger
  16. W http.ResponseWriter
  17. R *http.Request
  18. S *session.Session
  19. Host string
  20. Port string
  21. DConfig string
  22. DHtdocs string
  23. DLogs string
  24. DTemplate string
  25. DTmp string
  26. IsBackend bool
  27. ConfMysqlExists bool
  28. UrlArgs []string
  29. CurrModule string
  30. DB *sql.DB
  31. }
  32. func New(l *logger.Logger, w http.ResponseWriter, r *http.Request, s *session.Session, host, port, dirConfig, dirHtdocs, dirLogs, dirTemplate, dirTmp string) *Wrapper {
  33. return &Wrapper{
  34. l: l,
  35. W: w,
  36. R: r,
  37. S: s,
  38. Host: host,
  39. Port: port,
  40. DConfig: dirConfig,
  41. DHtdocs: dirHtdocs,
  42. DLogs: dirLogs,
  43. DTemplate: dirTemplate,
  44. DTmp: dirTmp,
  45. UrlArgs: []string{},
  46. CurrModule: "index",
  47. }
  48. }
  49. func (this *Wrapper) LogAccess(msg string) {
  50. this.l.Log(msg, this.R, false)
  51. }
  52. func (this *Wrapper) LogError(msg string) {
  53. this.l.Log(msg, this.R, true)
  54. }
  55. func (this *Wrapper) UseDatabase() error {
  56. if this.DB != nil {
  57. return errors.New("already connected to database")
  58. }
  59. if !utils.IsMySqlConfigExists(this.DConfig + string(os.PathSeparator) + "mysql.json") {
  60. return errors.New("can't read database configuration file")
  61. }
  62. mc, err := utils.MySqlConfigRead(this.DConfig + string(os.PathSeparator) + "mysql.json")
  63. if err != nil {
  64. return err
  65. }
  66. this.DB, err = sql.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
  67. if err != nil {
  68. return err
  69. }
  70. err = this.DB.Ping()
  71. if err != nil {
  72. this.DB.Close()
  73. return err
  74. }
  75. return nil
  76. }
  77. func (this *Wrapper) Write(data string) {
  78. this.W.Write([]byte(data))
  79. }
  80. func (this *Wrapper) MsgSuccess(msg string) {
  81. this.Write(fmt.Sprintf(
  82. `ShowSystemMsgSuccess('Success!', '%s', false);`,
  83. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  84. }
  85. func (this *Wrapper) MsgError(msg string) {
  86. this.Write(fmt.Sprintf(
  87. `ShowSystemMsgError('Error!', '%s', true);`,
  88. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  89. }