wrapper.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. User *utils.MySql_user
  32. }
  33. func New(l *logger.Logger, w http.ResponseWriter, r *http.Request, s *session.Session, host, port, dirConfig, dirHtdocs, dirLogs, dirTemplate, dirTmp string) *Wrapper {
  34. return &Wrapper{
  35. l: l,
  36. W: w,
  37. R: r,
  38. S: s,
  39. Host: host,
  40. Port: port,
  41. DConfig: dirConfig,
  42. DHtdocs: dirHtdocs,
  43. DLogs: dirLogs,
  44. DTemplate: dirTemplate,
  45. DTmp: dirTmp,
  46. UrlArgs: []string{},
  47. CurrModule: "",
  48. }
  49. }
  50. func (this *Wrapper) LogAccess(msg string) {
  51. this.l.Log(msg, this.R, false)
  52. }
  53. func (this *Wrapper) LogError(msg string) {
  54. this.l.Log(msg, this.R, true)
  55. }
  56. func (this *Wrapper) UseDatabase() error {
  57. if this.DB != nil {
  58. return errors.New("already connected to database")
  59. }
  60. if !utils.IsMySqlConfigExists(this.DConfig + string(os.PathSeparator) + "mysql.json") {
  61. return errors.New("can't read database configuration file")
  62. }
  63. mc, err := utils.MySqlConfigRead(this.DConfig + string(os.PathSeparator) + "mysql.json")
  64. if err != nil {
  65. return err
  66. }
  67. this.DB, err = sql.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
  68. if err != nil {
  69. return err
  70. }
  71. err = this.DB.Ping()
  72. if err != nil {
  73. this.DB.Close()
  74. return err
  75. }
  76. return nil
  77. }
  78. func (this *Wrapper) Write(data string) {
  79. this.W.Write([]byte(data))
  80. }
  81. func (this *Wrapper) MsgSuccess(msg string) {
  82. this.Write(fmt.Sprintf(
  83. `ShowSystemMsgSuccess('Success!', '%s', false);`,
  84. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  85. }
  86. func (this *Wrapper) MsgError(msg string) {
  87. this.Write(fmt.Sprintf(
  88. `ShowSystemMsgError('Error!', '%s', true);`,
  89. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  90. }