From ff299c42a71e7561b6238f7bf3b7bdd14df0fb0e Mon Sep 17 00:00:00 2001 From: Martin Geno Date: Tue, 4 Apr 2017 08:18:58 +0200 Subject: [PATCH] [TASK] improve draft of ProductExists --- models/product.go | 36 +++++++++++++++++++++++++++++++++--- models/product_test.go | 9 ++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/models/product.go b/models/product.go index 4a7d17c..94d7ef0 100644 --- a/models/product.go +++ b/models/product.go @@ -1,6 +1,36 @@ package models -// TODO DRAFT for a rest request to a other microservice -func ProductExists(id int64) (bool, error) { - return true, nil +import ( + "net/http" + "time" +) + +type boolMicroServiceCache struct { + LastCheck time.Time + Value bool +} + +var productExistCache map[int64]boolMicroServiceCache + +func init() { + productExistCache = make(map[int64]boolMicroServiceCache) +} + +func ProductExists(id int64) (bool, error) { + if cache, ok := productExistCache[id]; ok { + // cache for 5min + before := time.Now().Add(-time.Minute * 5) + if !cache.LastCheck.Before(before) { + return cache.Value, nil + } + } + + // TODO DRAFT for a rest request to a other microservice + res, err := http.Get("http://golang.org") + + productExistCache[id] = boolMicroServiceCache{ + LastCheck: time.Now(), + Value: (res.StatusCode == http.StatusOK), + } + return productExistCache[id].Value, err } diff --git a/models/product_test.go b/models/product_test.go index b10d3d0..0693bd0 100644 --- a/models/product_test.go +++ b/models/product_test.go @@ -8,8 +8,15 @@ import ( func TestProductExists(t *testing.T) { assert := assert.New(t) - ok, err := ProductExists(3) + ok, err := ProductExists(3) assert.True(ok) assert.NoError(err) + + // test cache + ok, err = ProductExists(3) + assert.True(ok) + assert.NoError(err) + + // WARNING: test cache after 5min skipped }