-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_resource_example_test.go
102 lines (81 loc) · 1.85 KB
/
handle_resource_example_test.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package rip
import (
"context"
"net/http"
"time"
"github.com/dolanor/rip/encoding/html"
"github.com/dolanor/rip/encoding/json"
)
func Example() {
up := newUserProvider()
ro := NewRouteOptions().
WithCodecs(json.Codec, html.NewEntityCodec("/users/"))
http.HandleFunc(HandleEntities("/users/", up, ro))
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
type user struct {
Name string `json:"name" xml:"name"`
EmailAddress string `json:"email_address" xml:"email_address"`
BirthDate time.Time `json:"birth_date" xml:"birth_date"`
}
func (u user) IDString() string {
return u.Name
}
func (u *user) IDFromString(s string) error {
u.Name = s
return nil
}
type UserProvider struct {
mem map[string]user
}
func newUserProvider() *UserProvider {
return &UserProvider{
mem: map[string]user{},
}
}
func (up *UserProvider) Create(ctx context.Context, u *user) (*user, error) {
up.mem[u.Name] = *u
return u, nil
}
func (up UserProvider) Get(ctx context.Context, idString string) (*user, error) {
u, ok := up.mem[idString]
if !ok {
return &user{}, ErrNotFound
}
return &u, nil
}
func (up *UserProvider) Delete(ctx context.Context, idString string) error {
_, ok := up.mem[idString]
if !ok {
return ErrNotFound
}
delete(up.mem, idString)
return nil
}
func (up *UserProvider) Update(ctx context.Context, u *user) error {
_, ok := up.mem[u.Name]
if !ok {
return ErrNotFound
}
up.mem[u.Name] = *u
return nil
}
func (up *UserProvider) List(ctx context.Context, offset, limit int) ([]*user, error) {
var users []*user
max := len(up.mem)
if offset > max {
offset = max
}
if offset+limit > max {
limit = max - offset
}
for _, u := range up.mem {
// we copy to avoid referring the same pointer that would get updated
u := u
users = append(users, &u)
}
return users[offset : offset+limit], nil
}