-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrouter.go
71 lines (55 loc) · 1.27 KB
/
router.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
package apifaker
import (
"fmt"
)
type RestMethod int
const (
GET RestMethod = 1 << (10 * iota)
POST
PUT
PATCH
DELETE
)
type Route struct {
// Method request method only supports GET, POST, PUT, PATCH, DELETE
Method RestMethod
// Path
Path string
}
type Router struct {
Model *Model
Routes []Route
apiFaker *ApiFaker
filePath string
}
func (r *Router) setRestRoutes() {
r.Routes = []Route{
// GET /collection
{GET, fmt.Sprintf("/%s", r.Model.Name)},
// GET /collection/:id
{GET, fmt.Sprintf("/%s/:id", r.Model.Name)},
// POST /collection
{POST, fmt.Sprintf("/%s", r.Model.Name)},
// PUT /collection
{PUT, fmt.Sprintf("/%s/:id", r.Model.Name)},
// PATCH /collection
{PATCH, fmt.Sprintf("/%s/:id", r.Model.Name)},
// DELETE /collection
{DELETE, fmt.Sprintf("/%s/:id", r.Model.Name)},
}
}
// SaveToFile
func (r *Router) SaveToFile() error {
return r.Model.SaveToFile(r.filePath)
}
// NewRouterWithPath allocates and returns a new Router with the givn file path
func NewRouterWithPath(path string, apiFaker *ApiFaker) (*Router, error) {
router := &Router{apiFaker: apiFaker, filePath: path}
model, err := NewModelWithPath(path, router)
if err != nil {
return nil, err
}
router.Model = model
router.setRestRoutes()
return router, err
}