github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/transports/middlewares/cachecontrol/cache.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package cachecontrol 19 20 import ( 21 "github.com/aacfactory/errors" 22 "github.com/aacfactory/fns/context" 23 "github.com/aacfactory/fns/runtime" 24 "time" 25 ) 26 27 type Cache interface { 28 Get(ctx context.Context, key []byte) (value []byte, has bool, err error) 29 Set(ctx context.Context, key []byte, value []byte, ttl time.Duration) (err error) 30 Close() 31 } 32 33 var ( 34 cacheKeyPrefix = []byte("fns:cachecontrol:") 35 ) 36 37 type DefaultCache struct{} 38 39 func (cache *DefaultCache) Get(ctx context.Context, key []byte) (value []byte, has bool, err error) { 40 store := runtime.SharedStore(ctx) 41 value, has, err = store.Get(ctx, append(cacheKeyPrefix, key...)) 42 if err != nil { 43 err = errors.Warning("fns: cache control store get failed").WithCause(err) 44 return 45 } 46 return 47 } 48 49 func (cache *DefaultCache) Set(ctx context.Context, key []byte, value []byte, ttl time.Duration) (err error) { 50 store := runtime.SharedStore(ctx) 51 err = store.SetWithTTL(ctx, append(cacheKeyPrefix, key...), value, ttl) 52 if err != nil { 53 err = errors.Warning("fns: cache control store set failed").WithCause(err) 54 return 55 } 56 return 57 } 58 59 func (cache *DefaultCache) Close() { 60 }