Skip to content
This repository was archived by the owner on May 11, 2025. It is now read-only.

Commit 168a1a9

Browse files
committed
add cache decorator
1 parent d446adc commit 168a1a9

4 files changed

Lines changed: 72 additions & 10 deletions

File tree

README.md

Whitespace-only changes.

cache.go

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
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
}

conf.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"fmt"
5-
"github.com/sirupsen/logrus"
65
"github.com/spf13/viper"
76
"math/rand"
87
"os"
@@ -65,9 +64,9 @@ func ReadConfig() {
6564

6665
viper.SetConfigFile("config.yaml")
6766
if err := viper.ReadInConfig(); err != nil {
68-
logrus.Fatalf("Failed to read config file: %v", err)
67+
logger.Fatalf("Failed to read config file: %v", err)
6968
}
7069
if err := viper.Unmarshal(&conf); err != nil {
71-
logrus.Fatalf("Failed to unmarshal config file: %v", err)
70+
logger.Fatalf("Failed to unmarshal config file: %v", err)
7271
}
7372
}

server.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import (
88
func RunServer() {
99
app := iris.Default()
1010
{
11-
app.Get("/user/{username:string}", UserAPI)
12-
app.Get("/repo/{username:string}/{repo:string}", RepoAPI)
11+
app.Get("/user/{username:string}", CachedHandler(UserAPI, "username"))
12+
app.Get("/repo/{username:string}/{repo:string}", CachedHandler(RepoAPI, "username", "password"))
1313
}
1414
app.Listen(fmt.Sprintf(":%d", conf.Server.Port))
1515
}
@@ -20,7 +20,7 @@ func UserAPI(ctx iris.Context) {
2020
if err != nil {
2121
ThrowError(ctx, err.Error(), code)
2222
} else {
23-
ctx.JSON(data)
23+
EndBody(ctx, data, "username")
2424
}
2525
}
2626

@@ -30,6 +30,6 @@ func RepoAPI(ctx iris.Context) {
3030
if err != nil {
3131
ThrowError(ctx, err.Error(), code)
3232
} else {
33-
ctx.JSON(data)
33+
EndBody(ctx, data, "username", "repo")
3434
}
3535
}

0 commit comments

Comments
 (0)