This repository has been archived by the owner on Dec 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
router.go
199 lines (163 loc) · 4.53 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
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
package hydrocarbon
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/fortytw2/hydrocarbon/public"
)
//go:generate bash -c "pushd ui && NODE_ENV=production yarn build && popd"
//go:generate bash -c "go-bindata -pkg public -mode 0644 -modtime 499137600 -o public/assets_generated.go ui/dist/..."
// ErrorHandler wraps up common error handling patterns for http routers
type ErrorHandler func(w http.ResponseWriter, r *http.Request) error
func (eh ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
writeErr(w, fmt.Errorf("%v", r))
}
}()
err := eh(w, r)
if err != nil {
writeErr(w, err)
}
}
func limitDecoder(r *http.Request, x interface{}) error {
return json.NewDecoder(io.LimitReader(r.Body, 1024*8)).Decode(x)
}
var (
statusOK = "success"
statusError = "error"
)
// writeSuccess is a helper for writing the same format of JSON for every reply
func writeSuccess(w http.ResponseWriter, x interface{}) error {
var s = struct {
Status string `json:"status"`
Data interface{} `json:"data,omitempty"`
}{
statusOK,
x,
}
w.WriteHeader(http.StatusOK)
return json.NewEncoder(w).Encode(s)
}
// writeErr is the only way to write an error
func writeErr(w http.ResponseWriter, uErr error) {
var s = struct {
Status string `json:"status"`
Error string `json:"error"`
}{
statusError,
uErr.Error(),
}
err := json.NewEncoder(w).Encode(s)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
// NewRouter configures a new http.Handler that serves hydrocarbon
func NewRouter(ua *UserAPI, fa *FeedAPI, rs *ReadStatusAPI, domain string) http.Handler {
fpr := &fixedPathRouter{
paths: make(map[string]http.Handler),
}
fs := http.FileServer(
&assetfs.AssetFS{
Asset: public.Asset,
AssetDir: public.AssetDir,
AssetInfo: public.AssetInfo,
Prefix: "ui/dist/static/",
})
fpr.static = http.StripPrefix("/static/", fs)
// serve the single page app for every other route, it has a 404 page builtin
fpr.def = ErrorHandler(func(w http.ResponseWriter, r *http.Request) error {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return nil
}
var buf []byte
if r.URL.Path == "/favicon.ico" {
w.Header().Set("Content-Type", "image/png")
buf = public.MustAsset("ui/dist/media/favicon.9a3c5f4f.ico")
} else {
w.Header().Set("Content-Type", "text/html")
buf = public.MustAsset("ui/dist/index.html")
}
_, err := w.Write(buf)
return err
})
routes := map[string]ErrorHandler{
// login tokens
"/v1/token/create": ua.RequestToken,
// payment managemnet
"/v1/payment/create": ua.CreatePayment,
// api keys
"/v1/key/create": ua.Activate,
"/v1/key/verify": ua.VerifyKey,
"/v1/key/delete": ua.Deactivate,
"/v1/key/list": ua.ListSessions,
// feed management
"/v1/feed/create": fa.AddFeed,
"/v1/feed/delete": fa.RemoveFeed,
// list all posts with no body for a feed
"/v1/feed/get": fa.GetFeed,
// folder management
"/v1/folder/create": fa.AddFolder,
// list all folders with the feed titles
"/v1/folder/list": fa.GetFolders,
// get a post
"/v1/post/get": fa.GetPost,
"/v1/post/read": rs.MarkRead,
}
for route, handler := range routes {
fpr.paths[route] = handler
}
if httpsOnly(domain) {
return redirectHTTPS(fpr)
}
return fpr
}
// fixedPathRouter is a brutally simple http router that can handle three cases
// a static file handler for /static/*
// a default handler that should serve index.html
// exact match HTTP POST routes
type fixedPathRouter struct {
// default
def http.Handler
static http.Handler
paths map[string]http.Handler
}
func (fpr *fixedPathRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "static") {
fpr.static.ServeHTTP(w, r)
return
}
h, ok := fpr.paths[r.URL.Path]
if ok {
if r.Method != http.MethodPost && !strings.Contains(r.URL.Path, "get") {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
h.ServeHTTP(w, r)
return
}
fpr.def.ServeHTTP(w, r)
}
func httpsOnly(domain string) bool {
u, err := url.Parse(domain)
if err != nil {
panic(err)
}
return u.Scheme == "https"
}
func redirectHTTPS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Forwarded-Proto") == "http" {
r.URL.Scheme = "https"
http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
return
}
next.ServeHTTP(w, r)
})
}