actions.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package actions
  2. import (
  3. "database/sql"
  4. _ "github.com/go-sql-driver/mysql"
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. "regexp"
  9. "strings"
  10. "golang-fave/engine/wrapper"
  11. utils "golang-fave/engine/wrapper/utils"
  12. )
  13. type Action struct {
  14. wrapper *wrapper.Wrapper
  15. db *sql.DB
  16. }
  17. func (this *Action) write(data string) {
  18. (*this.wrapper.W).Write([]byte(data))
  19. }
  20. func (this *Action) msg_show(title string, msg string) {
  21. this.write(fmt.Sprintf(
  22. `ModalShowMsg('%s', '%s');`,
  23. strings.Replace(strings.Replace(title, `'`, `’`, -1), `"`, `”`, -1),
  24. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  25. }
  26. func (this *Action) msg_success(msg string) {
  27. this.msg_show("Success", msg)
  28. }
  29. func (this *Action) msg_error(msg string) {
  30. this.msg_show("Error", msg)
  31. }
  32. func (this *Action) use_database() error {
  33. if this.db != nil {
  34. return errors.New("already connected to database")
  35. }
  36. if !utils.IsMySqlConfigExists(this.wrapper.DirVHostHome) {
  37. return errors.New("can't read database configuration file")
  38. }
  39. mc, err := utils.MySqlConfigRead(this.wrapper.DirVHostHome)
  40. if err != nil {
  41. return err
  42. }
  43. this.db, err = sql.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
  44. if err != nil {
  45. return err
  46. }
  47. err = this.db.Ping()
  48. if err != nil {
  49. this.db.Close()
  50. return err
  51. }
  52. return nil
  53. }
  54. func (this *Action) is_valid_email(email string) bool {
  55. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  56. return regexpe.MatchString(email)
  57. }
  58. func New(wrapper *wrapper.Wrapper) *Action {
  59. return &Action{wrapper, nil}
  60. }
  61. func (this *Action) Run() bool {
  62. if this.wrapper.R.Method != "POST" {
  63. return false
  64. }
  65. if err := this.wrapper.R.ParseForm(); err == nil {
  66. action := this.wrapper.R.FormValue("action")
  67. if action != "" {
  68. if _, ok := reflect.TypeOf(this).MethodByName("Action_" + action); ok {
  69. (*this.wrapper.W).Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  70. (*this.wrapper.W).Header().Set("Content-Type", "text/html; charset=utf-8")
  71. reflect.ValueOf(this).MethodByName("Action_" + action).Call([]reflect.Value{})
  72. return true
  73. }
  74. }
  75. }
  76. return false
  77. }