Code review (round 1)
This commit is contained in:
parent
7706bd9845
commit
b37cf02a6e
12 changed files with 78 additions and 23 deletions
|
@ -10,14 +10,14 @@ import (
|
|||
//
|
||||
// Example:
|
||||
//
|
||||
// lookup := func() (string, error) {
|
||||
// r, _ := http.Get("...")
|
||||
// s, _ := io.ReadAll(r.Body)
|
||||
// return string(s), nil
|
||||
// }
|
||||
// c := NewLookupCache[string](lookup, time.Hour)
|
||||
// fmt.Println(c.Get()) // Fetches the string via HTTP
|
||||
// fmt.Println(c.Get()) // Uses cached value
|
||||
// lookup := func() (string, error) {
|
||||
// r, _ := http.Get("...")
|
||||
// s, _ := io.ReadAll(r.Body)
|
||||
// return string(s), nil
|
||||
// }
|
||||
// c := NewLookupCache[string](lookup, time.Hour)
|
||||
// fmt.Println(c.Get()) // Fetches the string via HTTP
|
||||
// fmt.Println(c.Get()) // Uses cached value
|
||||
type LookupCache[T any] struct {
|
||||
value *T
|
||||
lookup func() (T, error)
|
||||
|
@ -26,8 +26,12 @@ type LookupCache[T any] struct {
|
|||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// LookupFunc is a function that is called by the LookupCache if the underlying
|
||||
// value is out-of-date. It returns the new value, or an error.
|
||||
type LookupFunc[T any] func() (T, error)
|
||||
|
||||
// NewLookupCache creates a new LookupCache with a given time-to-live (TTL)
|
||||
func NewLookupCache[T any](lookup func() (T, error), ttl time.Duration) *LookupCache[T] {
|
||||
func NewLookupCache[T any](lookup LookupFunc[T], ttl time.Duration) *LookupCache[T] {
|
||||
return &LookupCache[T]{
|
||||
value: nil,
|
||||
lookup: lookup,
|
||||
|
|
|
@ -2,6 +2,7 @@ package util
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"golang.org/x/time/rate"
|
||||
"io"
|
||||
"net/netip"
|
||||
"os"
|
||||
|
@ -245,6 +246,12 @@ func TestMinMax(t *testing.T) {
|
|||
require.Equal(t, 50, MinMax(50, 10, 99))
|
||||
}
|
||||
|
||||
func TestMax(t *testing.T) {
|
||||
require.Equal(t, 9, Max(1, 9))
|
||||
require.Equal(t, 9, Max(9, 1))
|
||||
require.Equal(t, rate.Every(time.Minute), Max(rate.Every(time.Hour), rate.Every(time.Minute)))
|
||||
}
|
||||
|
||||
func TestPointerFunctions(t *testing.T) {
|
||||
i, s, ti := Int(99), String("abc"), Time(time.Unix(99, 0))
|
||||
require.Equal(t, 99, *i)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue