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

Commit fae817e

Browse files
committed
cache request speed
1 parent af52d51 commit fae817e

2 files changed

Lines changed: 12 additions & 18 deletions

File tree

cache.go

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,22 +65,16 @@ func GetJSONCache(ctx iris.Context, key string) (value AnalysisData, ok bool) {
6565
return value, true
6666
}
6767

68-
func GenerateKey(ctx iris.Context, keys ...string) string {
69-
param := ""
70-
for _, key := range keys {
71-
value := ctx.Params().GetString(key)
72-
param += fmt.Sprintf("%s=%s;", key, value)
73-
}
74-
return fmt.Sprintf("%s?%s", ctx.Path(), param)
75-
}
76-
7768
// CachedHandler is a decorator for handlers to enable caching their response.
78-
func CachedHandler(h iris.Handler, params ...string) iris.Handler {
69+
func CachedHandler(h iris.Handler) iris.Handler {
7970
return func(ctx iris.Context) {
80-
key := GenerateKey(ctx, params...)
71+
path := ctx.Path()
8172

82-
data, ok := GetJSONCache(ctx, key)
73+
data, ok := GetJSONCache(ctx, path)
8374
if ok {
75+
if conf.Debug {
76+
logger.Debugf("Hit cache of %s", path)
77+
}
8478
EndBody(ctx, data)
8579
} else {
8680
h(ctx)
@@ -96,8 +90,8 @@ func EndBody(ctx iris.Context, data AnalysisData) {
9690
}
9791
}
9892

99-
func EndBodyWithCache(ctx iris.Context, data AnalysisData, params ...string) {
100-
err := SetJSONCache(ctx, GenerateKey(ctx, params...), data)
93+
func EndBodyWithCache(ctx iris.Context, data AnalysisData) {
94+
err := SetJSONCache(ctx, ctx.Path(), data)
10195
if err != nil {
10296
logger.Errorf("Failed to set cache: %s", err.Error())
10397
ThrowError(ctx, err.Error(), iris.StatusInternalServerError)

server.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@ import (
88
func RunServer() {
99
app := iris.Default()
1010
{
11-
app.Get("/user/{username:string}", CachedHandler(UserAPI, "username"))
12-
app.Get("/repo/{username:string}/{repo:string}", CachedHandler(RepoAPI, "username", "repo"))
11+
app.Get("/user/{username:string}", CachedHandler(UserAPI))
12+
app.Get("/repo/{username:string}/{repo:string}", CachedHandler(RepoAPI))
1313
}
1414
app.Listen(fmt.Sprintf(":%d", conf.Server.Port))
1515
}
1616

1717
func UserAPI(ctx iris.Context) {
1818
username := ctx.Params().Get("username")
1919
data := AnalysisUser(username)
20-
EndBodyWithCache(ctx, data, "username")
20+
EndBodyWithCache(ctx, data)
2121
}
2222

2323
func RepoAPI(ctx iris.Context) {
2424
username, repo := ctx.Params().Get("username"), ctx.Params().Get("repo")
2525
data := AnalysisRepo(username, repo)
26-
EndBodyWithCache(ctx, data, "username", "repo")
26+
EndBodyWithCache(ctx, data)
2727
}

0 commit comments

Comments
 (0)