-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathexample_test.go
99 lines (87 loc) · 1.95 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
package mongo_test
import (
"log"
"net/http"
"github.com/rs/cors"
"github.com/rs/rest-layer/resource"
"github.com/rs/rest-layer/rest"
"github.com/rs/rest-layer/schema"
mgo "gopkg.in/mgo.v2"
mongo "github.com/rs/rest-layer-mongo"
)
var (
user = schema.Schema{
Fields: schema.Fields{
"id": schema.IDField,
"created": schema.CreatedField,
"updated": schema.UpdatedField,
"name": {
Required: true,
Filterable: true,
Sortable: true,
Validator: &schema.String{
MaxLen: 150,
},
},
},
}
// Define a post resource schema
post = schema.Schema{
Fields: schema.Fields{
"id": schema.IDField,
"created": schema.CreatedField,
"updated": schema.UpdatedField,
"user": {
Required: true,
Filterable: true,
Validator: &schema.Reference{
Path: "users",
},
},
"public": {
Filterable: true,
Validator: &schema.Bool{},
},
"meta": {
Schema: &schema.Schema{
Fields: schema.Fields{
"title": {
Required: true,
Validator: &schema.String{
MaxLen: 150,
},
},
"body": {
Validator: &schema.String{
MaxLen: 100000,
},
},
},
},
},
},
}
)
func Example() {
session, err := mgo.Dial("")
if err != nil {
log.Fatalf("Can't connect to MongoDB: %s", err)
}
db := "test_rest_layer"
index := resource.NewIndex()
users := index.Bind("users", user, mongo.NewHandler(session, db, "users"), resource.Conf{
AllowedModes: resource.ReadWrite,
})
users.Bind("posts", "user", post, mongo.NewHandler(session, db, "posts"), resource.Conf{
AllowedModes: resource.ReadWrite,
})
api, err := rest.NewHandler(index)
if err != nil {
log.Fatalf("Invalid API configuration: %s", err)
}
http.Handle("/", cors.New(cors.Options{OptionsPassthrough: true}).Handler(api))
log.Print("Serving API on http://localhost:8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}