actions.go 2.0 KB

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