genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0

[TASK] improve draft of ProductExists

This commit is contained in:
Martin Geno 2017-04-04 08:18:58 +02:00
parent 9da367ff5a
commit ff299c42a7
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
2 changed files with 41 additions and 4 deletions

View File

@ -1,6 +1,36 @@
package models package models
// TODO DRAFT for a rest request to a other microservice import (
func ProductExists(id int64) (bool, error) { "net/http"
return true, nil "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
} }

View File

@ -8,8 +8,15 @@ import (
func TestProductExists(t *testing.T) { func TestProductExists(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
ok, err := ProductExists(3)
ok, err := ProductExists(3)
assert.True(ok) assert.True(ok)
assert.NoError(err) assert.NoError(err)
// test cache
ok, err = ProductExists(3)
assert.True(ok)
assert.NoError(err)
// WARNING: test cache after 5min skipped
} }