genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
hs_monolith/runtime/productcache.go

51 lines
1.2 KiB
Go
Raw Normal View History

2017-05-03 08:02:29 +02:00
// Package with supporting functionality to run the microservice
package runtime
import (
"fmt"
"net/http"
"time"
"github.com/genofire/hs_master-kss-monolith/lib/log"
"sync"
)
2017-05-03 08:02:29 +02:00
// URL to the microservice which manages the products (product catalogue)
var ProductURL string
2017-05-03 08:02:29 +02:00
// Struct tht holds the information on the microservice cache
type boolMicroServiceCache struct {
LastCheck time.Time
Value bool
}
2017-05-03 08:02:29 +02:00
// Cache for existing products
var productExistCache map[int64]boolMicroServiceCache
var productMutex sync.Mutex
2017-05-03 08:02:29 +02:00
// Function to initialize the cache for existing products
func init() {
productExistCache = make(map[int64]boolMicroServiceCache)
}
2017-05-03 08:02:29 +02:00
// Function to check on the other microservice (product catalogue) if the product exists
func ProductExists(id int64) (bool, error) {
productMutex.Lock()
defer productMutex.Unlock()
if cache, ok := productExistCache[id]; ok {
return cache.Value, nil
}
url := fmt.Sprintf(ProductURL, id)
2017-05-05 10:44:19 +02:00
log.Log.WithField("url", url).Info("does the product exist?")
res, err := http.Get(url)
if err != nil {
return false, err
}
productExistCache[id] = boolMicroServiceCache{
LastCheck: time.Now(),
Value: (res.StatusCode == http.StatusOK),
}
return productExistCache[id].Value, nil
}