@@ -2,6 +2,7 @@ package main
22
33import (
44 "context"
5+ "encoding/json"
56 "fmt"
67 "github.com/go-redis/redis/v8"
78 "github.com/kataras/iris/v12"
@@ -23,10 +24,72 @@ func SetupCache() {
2324 }
2425}
2526
26- func SetCache (ctx iris.Context , key string , value interface {} ) error {
27+ func SetCache (ctx iris.Context , key string , value string ) error {
2728 return cache .Set (ctx .Request ().Context (), key , value , conf .Redis .Expiration ).Err ()
2829}
2930
30- func GetCache (ctx iris.Context , key string ) (string , error ) {
31- return cache .Get (ctx .Request ().Context (), key ).Result ()
31+ func GetCache (ctx iris.Context , key string ) (val string , ok bool ) {
32+ val , err := cache .Get (ctx .Request ().Context (), key ).Result ()
33+ if err == redis .Nil {
34+ return "" , false
35+ } else if err != nil {
36+ return "" , false
37+ } else if val == "" {
38+ return "" , false
39+ }
40+ return val , true
41+ }
42+
43+ func SetJSONCache (ctx iris.Context , key string , value interface {}) error {
44+ val , err := json .Marshal (value )
45+ if err != nil {
46+ return err
47+ }
48+ return SetCache (ctx , key , string (val ))
49+ }
50+
51+ func GetJSONCache (ctx iris.Context , key string ) (value iris.Map , ok bool ) {
52+ val , ok := GetCache (ctx , key )
53+ if ! ok {
54+ return nil , false
55+ }
56+ err := json .Unmarshal ([]byte (val ), & value )
57+ if err != nil {
58+ return nil , false
59+ }
60+ return value , true
61+ }
62+
63+ func GenerateKey (ctx iris.Context , keys ... string ) string {
64+ param := ""
65+ for _ , key := range keys {
66+ value := ctx .Params ().GetString (key )
67+ param += fmt .Sprintf ("%s=%s;" , key , value )
68+ }
69+ return fmt .Sprintf ("%s?%s" , ctx .Path (), param )
70+ }
71+
72+ // CachedHandler is a decorator for handlers to enable caching their response.
73+ func CachedHandler (h iris.Handler , params ... string ) iris.Handler {
74+ return func (ctx iris.Context ) {
75+ key := GenerateKey (ctx , params ... )
76+
77+ result , ok := GetJSONCache (ctx , key )
78+ if ok {
79+ ctx .JSON (result )
80+ return
81+ }
82+
83+ h (ctx )
84+ }
85+ }
86+
87+ func EndBody (ctx iris.Context , value iris.Map , params ... string ) {
88+ err := SetJSONCache (ctx , GenerateKey (ctx , params ... ), value )
89+ if err != nil {
90+ logger .Errorf ("Failed to set cache: %s" , err .Error ())
91+ ThrowError (ctx , err .Error (), iris .StatusInternalServerError )
92+ return
93+ }
94+ ctx .JSON (value )
3295}
0 commit comments