josiahcarlson / redis-in-action

Example code from the book

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chapter02 Golang CacheRequest bug

gopherhiro opened this issue · comments

Here it should not be possible to cache and then call the callback function directly, so the correct way to write it would be:

if !r.CanCache(request)

func (r *Client) CacheRequest(request string, callback func(string) string) string {
	if !r.CanCache(request) {
		return callback(request)
	}

	pageKey := "cache:" + hashRequest(request)
	content := r.Conn.Get(pageKey).Val()

	if content == "" {
		content = callback(request)
		r.Conn.Set(pageKey, content, 300*time.Second)
	}
	return content
}