actions.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package actions
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "golang-fave/engine/sessions"
  7. )
  8. type hRun func(e *Action)
  9. type Action struct {
  10. W *http.ResponseWriter
  11. R *http.Request
  12. VHost string
  13. VHostHome string
  14. RemoteIp string
  15. Session *sessions.Session
  16. list map[string]hRun
  17. }
  18. func (e *Action) register(name string, handle hRun) {
  19. e.list[name] = handle
  20. }
  21. func (e *Action) write(data string) {
  22. (*e.W).Write([]byte(data))
  23. }
  24. func (e *Action) msg_show(title string, msg string) {
  25. e.write(fmt.Sprintf(
  26. `ModalShowMsg('%s', '%s');`,
  27. strings.Replace(strings.Replace(title, `'`, `’`, -1), `"`, `”`, -1),
  28. strings.Replace(strings.Replace(msg, `'`, `’`, -1), `"`, `”`, -1)))
  29. }
  30. func (e *Action) msg_success(msg string) {
  31. e.msg_show("Success", msg)
  32. }
  33. func (e *Action) msg_error(msg string) {
  34. e.msg_show("Error", msg)
  35. }
  36. func New(w *http.ResponseWriter, r *http.Request, vhost string, vhosthome string, remoteip string, session *sessions.Session) *Action {
  37. act := Action{w, r, vhost, vhosthome, remoteip, session, make(map[string]hRun)}
  38. // Register all action here
  39. act.register("mysql", action_mysql)
  40. act.register("signin", action_signin)
  41. return &act
  42. }
  43. func (e *Action) Call() bool {
  44. if e.R.Method != "POST" {
  45. return false
  46. }
  47. if err := e.R.ParseForm(); err == nil {
  48. action := e.R.FormValue("action")
  49. if action != "" {
  50. fn, ok := e.list[action]
  51. if ok {
  52. (*e.W).Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  53. (*e.W).Header().Set("Content-Type", "text/html; charset=utf-8")
  54. fn(e)
  55. return true
  56. }
  57. }
  58. }
  59. return false
  60. }