cache.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package engine
  2. import (
  3. "net/http"
  4. "github.com/xyproto/datablock"
  5. lua "github.com/xyproto/gopher-lua"
  6. )
  7. // DataToClient is a helper function for sending file data (that might be cached) to a HTTP client
  8. func (ac *Config) DataToClient(w http.ResponseWriter, req *http.Request, filename string, data []byte) {
  9. datablock.NewDataBlock(data, true).ToClient(w, req, filename, ac.ClientCanGzip(req), gzipThreshold)
  10. }
  11. // DataToClientModernBrowsers is a helper function for sending file data (that might be cached) to a HTTP client
  12. func DataToClientModernBrowsers(w http.ResponseWriter, req *http.Request, filename string, data []byte) {
  13. datablock.NewDataBlock(data, true).ToClient(w, req, filename, true, gzipThreshold)
  14. }
  15. // LoadCacheFunctions loads functions related to caching into the given Lua state
  16. func (ac *Config) LoadCacheFunctions(L *lua.LState) {
  17. const disabledMessage = "Caching is disabled"
  18. const clearedMessage = "Cache cleared"
  19. luaCacheStatsFunc := L.NewFunction(func(L *lua.LState) int {
  20. if ac.cache == nil {
  21. L.Push(lua.LString(disabledMessage))
  22. return 1 // number of results
  23. }
  24. info := ac.cache.Stats()
  25. // Return the string, but drop the final newline
  26. L.Push(lua.LString(info[:len(info)-1]))
  27. return 1 // number of results
  28. })
  29. // Return information about the cache use
  30. L.SetGlobal("CacheInfo", luaCacheStatsFunc)
  31. L.SetGlobal("CacheStats", luaCacheStatsFunc) // undocumented alias
  32. // Clear the cache
  33. L.SetGlobal("ClearCache", L.NewFunction(func(L *lua.LState) int {
  34. if ac.cache == nil {
  35. L.Push(lua.LString(disabledMessage))
  36. return 1 // number of results
  37. }
  38. ac.cache.Clear()
  39. L.Push(lua.LString(clearedMessage))
  40. return 1 // number of results
  41. }))
  42. // Try to load a file into the file cache, if it isn't already there
  43. L.SetGlobal("preload", L.NewFunction(func(L *lua.LState) int {
  44. filename := L.ToString(1)
  45. if ac.cache == nil {
  46. L.Push(lua.LBool(false))
  47. return 1 // number of results
  48. }
  49. // Don't read from disk if already in cache, hence "true"
  50. if _, err := ac.cache.Read(filename, true); err != nil {
  51. L.Push(lua.LBool(false))
  52. return 1 // number of results
  53. }
  54. L.Push(lua.LBool(true)) // success
  55. return 1 // number of results
  56. }))
  57. }