lua.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package data
  2. import (
  3. "os"
  4. cherryFile "github.com/cherry-game/cherry/extend/file"
  5. clog "github.com/cherry-game/cherry/logger"
  6. cherryProfile "github.com/cherry-game/cherry/profile"
  7. "github.com/go-redis/redis/v8"
  8. )
  9. type (
  10. luaRow struct {
  11. Name string `json:"name"`
  12. Path string `json:"path"`
  13. Desc string `json:"desc"`
  14. }
  15. luaConfig struct {
  16. maps map[string]*redis.Script
  17. }
  18. )
  19. func (p *luaConfig) Name() string {
  20. return "lua"
  21. }
  22. func (p *luaConfig) Init() {
  23. p.maps = map[string]*redis.Script{}
  24. }
  25. func (p *luaConfig) OnLoad(maps interface{}, _ bool) (int, error) {
  26. var list []*luaRow
  27. if err := DecodeData(maps, &list); err != nil {
  28. return 0, err
  29. }
  30. loadMaps := map[string]*redis.Script{}
  31. for index, row := range list {
  32. bytes, err := row.readFileBytes()
  33. if err != nil {
  34. clog.Panicf("read script error. [row = %d, %v], err = %s", index+1, row, err)
  35. }
  36. loadMaps[row.Name] = redis.NewScript(string(bytes))
  37. }
  38. p.maps = loadMaps
  39. return len(list), nil
  40. }
  41. func (p *luaConfig) OnAfterLoad(_ bool) {
  42. }
  43. func (p *luaConfig) Get(name string) (*redis.Script, bool) {
  44. value, found := p.maps[name]
  45. return value, found
  46. }
  47. func (p *luaRow) readFileBytes() ([]byte, error) {
  48. fullPath, err := cherryFile.JoinPath(cherryProfile.Path(), p.Path)
  49. if err != nil {
  50. return nil, err
  51. }
  52. bytes, err := os.ReadFile(fullPath)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return bytes, nil
  57. }