-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
647 lines (579 loc) · 20.4 KB
/
main.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
package issuesapp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/shurcooL/github_flavored_markdown"
"github.com/shurcooL/htmlg"
"github.com/shurcooL/httperror"
"github.com/shurcooL/httpfs/html/vfstemplate"
"github.com/shurcooL/httpgzip"
"github.com/shurcooL/issues"
"github.com/shurcooL/issuesapp/assets"
"github.com/shurcooL/issuesapp/common"
"github.com/shurcooL/issuesapp/component"
"github.com/shurcooL/notifications"
"github.com/shurcooL/octicon"
"github.com/shurcooL/reactions"
reactionscomponent "github.com/shurcooL/reactions/component"
"github.com/shurcooL/users"
"golang.org/x/net/html"
)
// TODO: Find a better way for issuesapp to be able to ensure registration of a top-level route:
//
// emojisHandler := httpgzip.FileServer(emojis.Assets, httpgzip.FileServerOptions{ServeError: httpgzip.Detailed})
// http.Handle("/emojis/", http.StripPrefix("/emojis", emojisHandler))
//
// So that it can depend on it.
// New returns an issues app http.Handler using given services and options.
// If usersService is nil, then there is no way to have an authenticated user.
// Emojis image data is expected to be available at /emojis/emojis.png, unless
// opt.DisableReactions is true.
//
// In order to serve HTTP requests, the returned http.Handler expects each incoming
// request to have 2 parameters provided to it via RepoSpecContextKey and BaseURIContextKey
// context keys. For example:
//
// issuesApp := issuesapp.New(...)
//
// http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// req = req.WithContext(context.WithValue(req.Context(), issuesapp.RepoSpecContextKey, issues.RepoSpec{...}))
// req = req.WithContext(context.WithValue(req.Context(), issuesapp.BaseURIContextKey, string(...)))
// issuesApp.ServeHTTP(w, req)
// })
//
// An HTTP API must be available (currently, only EditComment endpoint is used):
//
// // Register HTTP API endpoints.
// apiHandler := httphandler.Issues{Issues: service}
// http.Handle(httproute.List, errorHandler(apiHandler.List))
// http.Handle(httproute.Count, errorHandler(apiHandler.Count))
// http.Handle(httproute.ListComments, errorHandler(apiHandler.ListComments))
// http.Handle(httproute.ListEvents, errorHandler(apiHandler.ListEvents))
// http.Handle(httproute.EditComment, errorHandler(apiHandler.EditComment))
func New(service issues.Service, users users.Service, opt Options) http.Handler {
static, err := loadTemplates(common.State{}, opt.BodyPre)
if err != nil {
log.Fatalln("loadTemplates failed:", err)
}
h := handler{
is: service,
us: users,
static: static,
assetsFileServer: httpgzip.FileServer(assets.Assets, httpgzip.FileServerOptions{ServeError: httpgzip.Detailed}),
gfmFileServer: httpgzip.FileServer(assets.GFMStyle, httpgzip.FileServerOptions{ServeError: httpgzip.Detailed}),
Options: opt,
}
return &errorHandler{
handler: h.ServeHTTP,
users: users,
}
}
// RepoSpecContextKey is a context key for the request's repository specification.
// That value specifies which repo the issues are to be displayed for.
// The associated value will be of type issues.RepoSpec.
var RepoSpecContextKey = &contextKey{"RepoSpec"}
// BaseURIContextKey is a context key for the request's base URI.
// That value specifies the base URI prefix to use for all absolute URLs.
// The associated value will be of type string.
var BaseURIContextKey = &contextKey{"BaseURI"}
// StateContextKey is a context key for the request's common state.
// That value specifies the common state of the page being rendered.
// The associated value will be of type common.State.
var StateContextKey = &contextKey{"State"}
// Options for configuring issues app.
type Options struct {
Notifications notifications.Service // If not nil, issues containing unread notifications are highlighted.
DisableReactions bool // Disable all support for displaying and toggling reactions.
HeadPre, HeadPost template.HTML
BodyPre string // An html/template definition of "body-pre" template.
// BodyTop provides components to include on top of <body> of page rendered for req. It can be nil.
// StateContextKey can be used to get the common state value.
BodyTop func(req *http.Request) ([]htmlg.Component, error)
// SignIn returns HTML with a link or button to sign in. It can be nil.
SignIn func(returnURL string) template.HTML
}
// handler handles all requests to issuesapp. It acts like a request multiplexer,
// choosing from various endpoints and parsing the repository ID from URL.
type handler struct {
is issues.Service
us users.Service // May be nil if there's no users service.
assetsFileServer http.Handler
gfmFileServer http.Handler
// static is loaded once in New, and is only for rendering templates that don't use state.
static *template.Template
Options
}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) error {
if _, ok := req.Context().Value(RepoSpecContextKey).(issues.RepoSpec); !ok {
return fmt.Errorf("request to %v doesn't have issuesapp.RepoSpecContextKey context key set", req.URL.Path)
}
if _, ok := req.Context().Value(BaseURIContextKey).(string); !ok {
return fmt.Errorf("request to %v doesn't have issuesapp.BaseURIContextKey context key set", req.URL.Path)
}
// Handle "/assets/gfm/...".
if strings.HasPrefix(req.URL.Path, "/assets/gfm/") {
req = stripPrefix(req, len("/assets/gfm"))
h.gfmFileServer.ServeHTTP(w, req)
return nil
}
// Handle "/assets/script.js".
if req.URL.Path == "/assets/script.js" {
req = stripPrefix(req, len("/assets"))
h.assetsFileServer.ServeHTTP(w, req)
return nil
}
// Handle (the rest of) "/assets/...".
if strings.HasPrefix(req.URL.Path, "/assets/") {
h.assetsFileServer.ServeHTTP(w, req)
return nil
}
// Handle "/".
if req.URL.Path == "/" {
return h.IssuesHandler(w, req)
}
// Handle "/new".
if req.URL.Path == "/new" {
return h.serveNewIssue(w, req)
}
// Handle "/{issueID}" and "/{issueID}/...".
elems := strings.SplitN(req.URL.Path[1:], "/", 3)
issueID, err := strconv.ParseUint(elems[0], 10, 64)
if err != nil {
return httperror.HTTP{Code: http.StatusNotFound, Err: fmt.Errorf("invalid issue ID %q: %v", elems[0], err)}
}
switch {
// "/{issueID}".
case len(elems) == 1:
return h.IssueHandler(w, req, issueID)
// "/{issueID}/edit".
case len(elems) == 2 && elems[1] == "edit":
return h.PostEditIssueHandler(w, req, issueID)
// "/{issueID}/comment".
case len(elems) == 2 && elems[1] == "comment":
return h.PostCommentHandler(w, req, issueID)
default:
return httperror.HTTP{Code: http.StatusNotFound, Err: errors.New("no route")}
}
}
func (h *handler) IssuesHandler(w http.ResponseWriter, req *http.Request) error {
if req.Method != http.MethodGet {
return httperror.Method{Allowed: []string{http.MethodGet}}
}
state, err := h.state(req, 0)
if err != nil {
return err
}
filter, err := stateFilter(req.URL.Query())
if err != nil {
return httperror.BadRequest{Err: err}
}
is, err := h.is.List(req.Context(), state.RepoSpec, issues.IssueListOptions{State: filter})
if err != nil {
return err
}
openCount, err := h.is.Count(req.Context(), state.RepoSpec, issues.IssueListOptions{State: issues.StateFilter(issues.OpenState)})
if err != nil {
return fmt.Errorf("issues.Count(open): %v", err)
}
closedCount, err := h.is.Count(req.Context(), state.RepoSpec, issues.IssueListOptions{State: issues.StateFilter(issues.ClosedState)})
if err != nil {
return fmt.Errorf("issues.Count(closed): %v", err)
}
var es []component.IssueEntry
for _, i := range is {
es = append(es, component.IssueEntry{Issue: i, BaseURI: state.BaseURI})
}
es = state.augmentUnread(req.Context(), es, h.is, h.Notifications)
state.Issues = component.Issues{
IssuesNav: component.IssuesNav{
OpenCount: openCount,
ClosedCount: closedCount,
Path: state.BaseURI + state.ReqPath,
Query: req.URL.Query(),
StateQueryKey: stateQueryKey,
},
Filter: filter,
Entries: es,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err = h.static.ExecuteTemplate(w, "issues.html.tmpl", &state)
if err != nil {
return fmt.Errorf("h.static.ExecuteTemplate: %v", err)
}
return nil
}
const (
// stateQueryKey is name of query key for controlling issue state filter.
stateQueryKey = "state"
)
// stateFilter parses the issue state filter from query,
// returning an error if the value is unsupported.
func stateFilter(query url.Values) (issues.StateFilter, error) {
selectedTabName := query.Get(stateQueryKey)
switch selectedTabName {
case "":
return issues.StateFilter(issues.OpenState), nil
case "closed":
return issues.StateFilter(issues.ClosedState), nil
case "all":
return issues.AllStates, nil
default:
return "", fmt.Errorf("unsupported state filter value: %q", selectedTabName)
}
}
func (s state) augmentUnread(ctx context.Context, es []component.IssueEntry, is issues.Service, notificationsService notifications.Service) []component.IssueEntry {
if notificationsService == nil {
return es
}
tt, ok := is.(interface {
ThreadType(issues.RepoSpec) string
})
if !ok {
log.Println("augmentUnread: issues service doesn't implement ThreadType")
return es
}
if s.CurrentUser.ID == 0 {
// Unauthenticated user cannot have any unread issues.
return es
}
// TODO: Consider starting to do this in background in parallel with is.List.
ns, err := notificationsService.List(ctx, notifications.ListOptions{
Repo: ¬ifications.RepoSpec{URI: s.RepoSpec.URI},
})
if err != nil {
log.Println("augmentUnread: failed to notifications.List:", err)
return es
}
unreadThreads := make(map[uint64]struct{}) // Set of unread thread IDs.
for _, n := range ns {
// n.RepoSpec == s.RepoSpec is guaranteed because we filtered in notifications.ListOptions,
// so we only need to check that n.ThreadType matches.
if n.ThreadType != tt.ThreadType(s.RepoSpec) {
continue
}
unreadThreads[n.ThreadID] = struct{}{}
}
for i, e := range es {
_, unread := unreadThreads[e.Issue.ID]
es[i].Unread = unread
}
return es
}
func (h *handler) IssueHandler(w http.ResponseWriter, req *http.Request, issueID uint64) error {
if req.Method != http.MethodGet {
return httperror.Method{Allowed: []string{http.MethodGet}}
}
state, err := h.state(req, issueID)
if err != nil {
return err
}
state.Issue, err = h.is.Get(req.Context(), state.RepoSpec, state.IssueID)
if err != nil {
return err
}
var items []issueItem
switch is, ok := h.is.(issues.TimelineLister); ok && is.IsTimelineLister(state.RepoSpec) {
case true:
tis, err := is.ListTimeline(req.Context(), state.RepoSpec, state.IssueID, nil)
if err != nil {
return fmt.Errorf("issues.ListTimeline: %v", err)
}
for _, timelineItem := range tis {
items = append(items, issueItem{timelineItem})
}
case false:
cs, err := h.is.ListComments(req.Context(), state.RepoSpec, state.IssueID, nil)
if err != nil {
return fmt.Errorf("issues.ListComments: %v", err)
}
es, err := h.is.ListEvents(req.Context(), state.RepoSpec, state.IssueID, nil)
if err != nil {
return fmt.Errorf("issues.ListEvents: %v", err)
}
for _, comment := range cs {
items = append(items, issueItem{comment})
}
for _, event := range es {
items = append(items, issueItem{event})
}
sort.Sort(byCreatedAtID(items))
}
state.Items = items
// Call loadTemplates to set updated reactionsBar, reactableID, etc., template functions.
t, err := loadTemplates(state.State, h.Options.BodyPre)
if err != nil {
return fmt.Errorf("loadTemplates: %v", err)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err = t.ExecuteTemplate(w, "issue.html.tmpl", &state)
if err != nil {
return fmt.Errorf("t.ExecuteTemplate: %v", err)
}
return nil
}
func (h *handler) serveNewIssue(w http.ResponseWriter, req *http.Request) error {
switch req.Method {
case http.MethodGet:
return h.CreateIssueHandler(w, req)
case http.MethodPost:
return h.PostCreateIssueHandler(w, req)
default:
return httperror.Method{Allowed: []string{http.MethodGet, http.MethodPost}}
}
}
func (h *handler) CreateIssueHandler(w http.ResponseWriter, req *http.Request) error {
state, err := h.state(req, 0)
if err != nil {
return err
}
if state.CurrentUser.ID == 0 {
return os.ErrPermission
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err = h.static.ExecuteTemplate(w, "new-issue.html.tmpl", &state)
if err != nil {
return fmt.Errorf("h.static.ExecuteTemplate: %v", err)
}
return nil
}
func (h *handler) PostCreateIssueHandler(w http.ResponseWriter, req *http.Request) error {
repoSpec := req.Context().Value(RepoSpecContextKey).(issues.RepoSpec)
baseURI := req.Context().Value(BaseURIContextKey).(string)
var issue issues.Issue
err := json.NewDecoder(req.Body).Decode(&issue)
if err != nil {
return httperror.BadRequest{Err: fmt.Errorf("json.Decode: %v", err)}
}
issue, err = h.is.Create(req.Context(), repoSpec, issue)
if err != nil {
return err
}
fmt.Fprintf(w, "%s/%d", baseURI, issue.ID)
return nil
}
func (h *handler) PostEditIssueHandler(w http.ResponseWriter, req *http.Request, issueID uint64) error {
if req.Method != http.MethodPost {
return httperror.Method{Allowed: []string{http.MethodPost}}
}
if err := req.ParseForm(); err != nil {
return httperror.BadRequest{Err: fmt.Errorf("req.ParseForm: %v", err)}
}
repoSpec := req.Context().Value(RepoSpecContextKey).(issues.RepoSpec)
var ir issues.IssueRequest
err := json.Unmarshal([]byte(req.PostForm.Get("value")), &ir)
if err != nil {
return httperror.BadRequest{Err: fmt.Errorf("json.Unmarshal 'value': %v", err)}
}
issue, events, err := h.is.Edit(req.Context(), repoSpec, issueID, ir)
if err != nil {
return err
}
resp := make(url.Values)
// State badge.
var buf bytes.Buffer
err = htmlg.RenderComponents(&buf, component.IssueStateBadge{Issue: issue})
if err != nil {
return err
}
resp.Set("issue-state-badge", buf.String())
// Toggle button.
buf.Reset()
err = h.static.ExecuteTemplate(&buf, "toggle-button", issue.State)
if err != nil {
return err
}
resp.Set("issue-toggle-button", buf.String())
// Events.
for _, event := range events {
buf.Reset()
err = htmlg.RenderComponents(&buf, component.Event{Event: event})
if err != nil {
return err
}
resp.Add("new-event", buf.String())
}
_, err = io.WriteString(w, resp.Encode())
return err
}
func (h *handler) PostCommentHandler(w http.ResponseWriter, req *http.Request, issueID uint64) error {
if req.Method != http.MethodPost {
return httperror.Method{Allowed: []string{http.MethodPost}}
}
if err := req.ParseForm(); err != nil {
return httperror.BadRequest{Err: fmt.Errorf("req.ParseForm: %v", err)}
}
state, err := h.state(req, issueID)
if err != nil {
return err
}
comment := issues.Comment{
Body: req.PostForm.Get("value"),
}
comment, err = h.is.CreateComment(req.Context(), state.RepoSpec, issueID, comment)
if err != nil {
return err
}
// Call loadTemplates to set updated reactionsBar, reactableID, etc., template functions.
t, err := loadTemplates(state.State, h.Options.BodyPre)
if err != nil {
return fmt.Errorf("loadTemplates: %v", err)
}
err = t.ExecuteTemplate(w, "comment", comment)
if err != nil {
return fmt.Errorf("t.ExecuteTemplate: %v", err)
}
return nil
}
func (h *handler) state(req *http.Request, issueID uint64) (state, error) {
// TODO: Caller still does a lot of work outside to calculate req.URL.Path by
// subtracting BaseURI from full original req.URL.Path. We should be able
// to compute it here internally by using req.RequestURI and BaseURI.
reqPath := req.URL.Path
if reqPath == "/" {
reqPath = "" // This is needed so that absolute URL for root view, i.e., /issues, is "/issues" and not "/issues/" because of "/issues" + "/".
}
b := state{
State: common.State{
BaseURI: req.Context().Value(BaseURIContextKey).(string),
ReqPath: reqPath,
RepoSpec: req.Context().Value(RepoSpecContextKey).(issues.RepoSpec),
IssueID: issueID,
},
}
b.HeadPre = h.HeadPre
b.HeadPost = h.HeadPost
if h.BodyTop != nil {
c, err := h.BodyTop(req.WithContext(context.WithValue(req.Context(), StateContextKey, b.State)))
if err != nil {
return state{}, err
}
var buf bytes.Buffer
err = htmlg.RenderComponents(&buf, c...)
if err != nil {
return state{}, fmt.Errorf("htmlg.RenderComponents: %v", err)
}
b.BodyTop = template.HTML(buf.String())
}
b.DisableReactions = h.Options.DisableReactions
b.DisableUsers = h.us == nil
if h.Options.SignIn != nil {
returnURL := b.BaseURI + b.ReqPath
b.SignIn = h.Options.SignIn(returnURL)
}
if h.us == nil {
// No user service provided, so there can never be an authenticated user.
b.CurrentUser = users.User{}
} else if user, err := h.us.GetAuthenticated(req.Context()); err == nil {
b.CurrentUser = user
} else {
return state{}, fmt.Errorf("h.us.GetAuthenticated: %v", err)
}
b.ForceIssuesApp, _ = strconv.ParseBool(req.URL.Query().Get("issuesapp"))
return b, nil
}
type state struct {
HeadPre, HeadPost template.HTML
BodyTop template.HTML
SignIn template.HTML
common.State
Issues component.Issues
Issue issues.Issue
Items []issueItem
// ForceIssuesApp reports whether "issuesapp" query is true.
// This is a temporary solution for external users to use when overriding templates.
// It's going to go away eventually, so its use is discouraged.
ForceIssuesApp bool
}
func loadTemplates(state common.State, bodyPre string) (*template.Template, error) {
t := template.New("").Funcs(template.FuncMap{
"json": func(v interface{}) (string, error) {
b, err := json.Marshal(v)
return string(b), err
},
"jsonfmt": func(v interface{}) (string, error) {
b, err := json.MarshalIndent(v, "", "\t")
return string(b), err
},
"reltime": humanize.Time,
"gfm": func(s string) template.HTML { return template.HTML(github_flavored_markdown.Markdown([]byte(s))) },
"reactionPosition": func(emojiID reactions.EmojiID) string { return reactions.Position(":" + string(emojiID) + ":") },
"equalUsers": func(a, b users.User) bool {
return a.UserSpec == b.UserSpec
},
"reactableID": func(commentID uint64) string {
return fmt.Sprintf("%d/%d", state.IssueID, commentID)
},
"reactionsBar": func(reactions []reactions.Reaction, reactableID string) htmlg.Component {
return reactionscomponent.ReactionsBar{
Reactions: reactions,
CurrentUser: state.CurrentUser,
ID: reactableID,
}
},
"newReaction": func(reactableID string) htmlg.Component {
return reactionscomponent.NewReaction{
ReactableID: reactableID,
}
},
"state": func() common.State { return state },
"octicon": func(name string) (template.HTML, error) {
icon := octicon.Icon(name)
if icon == nil {
return "", fmt.Errorf("%q is not a valid Octicon symbol name", name)
}
var buf bytes.Buffer
err := html.Render(&buf, icon)
if err != nil {
return "", err
}
return template.HTML(buf.String()), nil
},
"render": func(c htmlg.Component) template.HTML {
return template.HTML(htmlg.Render(c.Render()...))
},
"event": func(e issues.Event) htmlg.Component { return component.Event{Event: e} },
"issueStateBadge": func(i issues.Issue) htmlg.Component { return component.IssueStateBadge{Issue: i} },
"time": func(t time.Time) htmlg.Component { return component.Time{Time: t} },
"user": func(u users.User) htmlg.Component { return component.User{User: u} },
"avatar": func(u users.User) htmlg.Component { return component.Avatar{User: u, Size: 48} },
})
t, err := vfstemplate.ParseGlob(assets.Assets, t, "/assets/*.tmpl")
if err != nil {
return nil, err
}
return t.New("body-pre").Parse(bodyPre)
}
// contextKey is a value for use with context.WithValue. It's used as
// a pointer so it fits in an interface{} without allocation.
type contextKey struct {
name string
}
func (k *contextKey) String() string { return "github.com/shurcooL/issuesapp context value " + k.name }
// stripPrefix returns request r with prefix of length prefixLen stripped from r.URL.Path.
// prefixLen must not be longer than len(r.URL.Path), otherwise stripPrefix panics.
// If r.URL.Path is empty after the prefix is stripped, the path is changed to "/".
func stripPrefix(r *http.Request, prefixLen int) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = r.URL.Path[prefixLen:]
if r2.URL.Path == "" {
r2.URL.Path = "/"
}
return r2
}