forked from rs/rest-layer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
232 lines (207 loc) · 6.33 KB
/
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package restlayer
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/rs/cors"
"github.com/rs/rest-layer/resource"
"github.com/rs/rest-layer/resource/testing/mem"
"github.com/rs/rest-layer/rest"
"github.com/rs/rest-layer/schema"
)
// ResponseRecorder extends http.ResponseWriter with the ability to capture
// the status and number of bytes written
type ResponseRecorder struct {
http.ResponseWriter
statusCode int
length int
}
// NewResponseRecorder returns a ResponseRecorder that wraps w.
func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder {
return &ResponseRecorder{ResponseWriter: w, statusCode: http.StatusOK}
}
// Write writes b to the underlying response writer and stores how many bytes
// have been written.
func (w *ResponseRecorder) Write(b []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(b)
w.length += n
return
}
// WriteHeader stores and writes the HTTP status code.
func (w *ResponseRecorder) WriteHeader(code int) {
w.statusCode = code
w.ResponseWriter.WriteHeader(code)
}
// StatusCode returns the status-code written to the response or 200 (OK).
func (w *ResponseRecorder) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
func AccessLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := NewResponseRecorder(w)
next.ServeHTTP(rec, r)
status := rec.StatusCode()
length := rec.length
// In this example we use the standard library logger. Structured logs
// may prove more parsable in a production environment.
log.Printf("D! Served HTTP Request %s %s with Response %d %s [%d bytes] in %d ms",
r.Method,
r.URL,
status,
http.StatusText(status),
length,
time.Since(start).Nanoseconds()/1e6,
)
})
}
var logLevelPrefixes = map[resource.LogLevel]string{
resource.LogLevelFatal: "E!",
resource.LogLevelError: "E!",
resource.LogLevelWarn: "W!",
resource.LogLevelInfo: "I!",
resource.LogLevelDebug: "D!",
}
func Example() {
// Configure a log-addapter for the resource pacakge.
resource.LoggerLevel = resource.LogLevelDebug
resource.Logger = func(ctx context.Context, level resource.LogLevel, msg string, fields map[string]interface{}) {
fmt.Printf("%s %s %v", logLevelPrefixes[level], msg, fields)
}
var (
// Define a user resource schema
user = schema.Schema{
Fields: schema.Fields{
"id": {
Required: true,
// When a field is read-only, on default values or hooks can
// set their value. The client can't change it.
ReadOnly: true,
// This is a field hook called when a new user is created.
// The schema.NewID hook is a provided hook to generate a
// unique id when no value is provided.
OnInit: schema.NewID,
// The Filterable and Sortable allows usage of filter and sort
// on this field in requests.
Filterable: true,
Sortable: true,
Validator: &schema.String{
Regexp: "^[0-9a-f]{32}$",
},
},
"created": {
Required: true,
ReadOnly: true,
Filterable: true,
Sortable: true,
OnInit: schema.Now,
Validator: &schema.Time{},
},
"updated": {
Required: true,
ReadOnly: true,
Filterable: true,
Sortable: true,
OnInit: schema.Now,
// The OnUpdate hook is called when the item is edited. Here we use
// provided Now hook which just return the current time.
OnUpdate: schema.Now,
Validator: &schema.Time{},
},
// Define a name field as required with a string validator
"name": {
Required: true,
Filterable: true,
Validator: &schema.String{
MaxLen: 150,
},
},
},
}
// Define a post resource schema
post = schema.Schema{
Fields: schema.Fields{
// schema.*Field are shortcuts for common fields (identical to users' same fields)
"id": schema.IDField,
"created": schema.CreatedField,
"updated": schema.UpdatedField,
// Define a user field which references the user owning the post.
// See bellow, the content of this field is enforced by the fact
// that posts is a sub-resource of users.
"user": {
Required: true,
Filterable: true,
Validator: &schema.Reference{
Path: "users",
},
},
"public": {
Filterable: true,
Validator: &schema.Bool{},
},
// Sub-documents are handled via a sub-schema
"meta": {
Schema: &schema.Schema{
Fields: schema.Fields{
"title": {
Required: true,
Validator: &schema.String{
MaxLen: 150,
},
},
"body": {
Validator: &schema.String{
MaxLen: 100000,
},
},
},
},
},
},
}
)
// Create a REST API root resource.
index := resource.NewIndex()
// Add a resource on /users[/:user_id]
users := index.Bind("users", user, mem.NewHandler(), resource.Conf{
// We allow all REST methods.
// (rest.ReadWrite is a shortcut for []rest.Mode{Create, Read, Update, Delete, List})
AllowedModes: resource.ReadWrite,
})
// Bind a sub resource on /users/:user_id/posts[/:post_id]
// and reference the user on each post using the "user" field of the posts resource.
posts := users.Bind("posts", "user", post, mem.NewHandler(), resource.Conf{
// Posts can only be read, created and deleted, not updated
AllowedModes: []resource.Mode{resource.Read, resource.List, resource.Create, resource.Delete},
})
// Add a friendly alias to public posts.
// (equivalent to /users/:user_id/posts?filter={"public":true})
posts.Alias("public", url.Values{"filter": []string{"{\"public\"=true}"}})
// Create API HTTP handler for the resource graph.
var api http.Handler
api, err := rest.NewHandler(index)
if err != nil {
log.Printf("E! Invalid API configuration: %s", err)
os.Exit(1)
}
// Add CORS support with passthrough option on so rest-layer can still
// handle OPTIONS method.
api = cors.New(cors.Options{OptionsPassthrough: true}).Handler(api)
// Wrap the api & cors handler with an access log middleware.
api = AccessLog(api)
// Bind the API under the /api/ path.
http.Handle("/api/", http.StripPrefix("/api/", api))
// Serve it.
log.Printf("I! Serving API on http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Printf("E! Cannot serve API: %s", err)
os.Exit(1)
}
}