cache.go 837 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package cache
  2. import (
  3. bm "go-common/library/net/http/blademaster"
  4. "go-common/library/net/http/blademaster/middleware/cache/store"
  5. )
  6. // Cache is the abstract struct for any cache impl
  7. type Cache struct {
  8. store store.Store
  9. }
  10. // Filter is used to check is cache required for every request
  11. type Filter func(*bm.Context) bool
  12. // Policy is used to abstract different cache policy
  13. type Policy interface {
  14. Key(*bm.Context) string
  15. Handler(store.Store) bm.HandlerFunc
  16. }
  17. // New will create a new Cache struct
  18. func New(store store.Store) *Cache {
  19. c := &Cache{
  20. store: store,
  21. }
  22. return c
  23. }
  24. // Cache is used to mark path as customized cache policy
  25. func (c *Cache) Cache(policy Policy, filter Filter) bm.HandlerFunc {
  26. return func(ctx *bm.Context) {
  27. if filter != nil && !filter(ctx) {
  28. return
  29. }
  30. policy.Handler(c.store)(ctx)
  31. }
  32. }