-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
80 lines (66 loc) · 1.95 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
72
73
74
75
76
77
78
79
80
package v1
import (
"context"
"errors"
"net/http"
"github.com/ethicalapps/ucms/cms"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
// Router defines the routes for the v1 API
func Router() http.Handler {
r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Route("/{repository}", func(r chi.Router) {
r.Use(repositoryCtx)
r.Get("/type/{contentType}.json", getContentType)
r.Get("/schema/{contentType}.json", getSchema)
r.Get("/{contentType}/{contentID}.json", getDocument)
r.Get("/{contentType}", listDocuments)
r.Group(func(r chi.Router) {
r.Use(authentication)
r.Put("/type/{contentType}.json", putContentType)
r.Put("/{contentType}/{contentID}.json", putDocument)
})
r.NotFound(notFound)
r.MethodNotAllowed(methodNotAllowed)
})
return r
}
type contextKey string
var (
contextKeyRepo = contextKey("repo")
urlParamRepository = "repository"
urlParamContentType = "contentType"
urlParamContentID = "contentID"
)
func repositoryCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
repositoryName := chi.URLParam(r, urlParamRepository)
repo, err := cms.NewRepository(repositoryName)
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
ctx := context.WithValue(r.Context(), contextKeyRepo, repo)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FIXME: implement authentication
if true {
next.ServeHTTP(w, r)
} else {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
}
})
}
func notFound(w http.ResponseWriter, r *http.Request) {
err := errors.New("route not found")
render.Render(w, r, ErrNotFound(err))
}
func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
err := errors.New("method not allowed")
render.Render(w, r, ErrNotFound(err))
}