-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathproxy.go
62 lines (51 loc) · 1.19 KB
/
proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package proxy
import (
"fmt"
)
type User struct {
ID int32
}
type UserFinder interface {
FindUser(id int32) (User, error)
}
type UserList []User
type UserListProxy struct {
SomeDatabase UserList
StackCache UserList
StackCapacity int
DidLastSearchUsedCache bool
}
func (u *UserListProxy) FindUser(ID int32) (User, error) {
user, err := u.StackCache.FindUser(ID)
if err == nil {
fmt.Println("Returning user from cache")
u.DidLastSearchUsedCache = true
return user, nil
}
user, err = u.SomeDatabase.FindUser(ID)
if err == nil {
fmt.Println("Returning user from database")
u.addUserToStack(user)
u.DidLastSearchUsedCache = false
return user, nil
}
return User{}, fmt.Errorf("User not found")
}
func (u *UserListProxy) addUserToStack(user User) {
if len(u.StackCache) >= u.StackCapacity {
u.StackCache = append(u.StackCache[1:], user)
} else {
u.StackCache.addUser(user)
}
}
func (u *UserList) addUser(newUser User) {
*u = append(*u, newUser)
}
func (u *UserList) FindUser(id int32) (User, error) {
for i := 0; i < len(*u); i++ {
if (*u)[i].ID == id {
return (*u)[i], nil
}
}
return User{}, fmt.Errorf("User %d could not be found\n", id)
}