-
Notifications
You must be signed in to change notification settings - Fork 0
/
next.go
85 lines (72 loc) · 2.25 KB
/
next.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
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package pt
import (
"net/http"
"net/url"
"strings"
)
// NextKey is the query param name used when redirecting.
var NextKey = "next"
// This can be used within templates like..:
// <a href="/auth/login{% if url.Path != '/' %}?next={{ url.Path|urlencode }}{% endif %}</a>
//
// Or maybe:
// <input type="hidden" name="next" value="{{ url.Query().Get('next') }}">
// GetNextURL obtains the target url from the intermediary URL, allowing you
// to pass in a URL parameter (e.g. ?next=/some/authed/page) which you can
// redirect to after doing some task (e.g. authenticating).
//
// For example:
// if isAuthed(r) {
// if next := pt.GetNextURL(r); next != "" {
// pt.RedirectToNextURL(w, r, http.StatusFound)
// return
// }
//
// http.Redirect(w, r, "/some/home/page", http.StatusFound)
// return
// }
func GetNextURL(r *http.Request) (next string) {
_ = r.ParseForm()
if next = r.URL.Query().Get(NextKey); next == "" {
next = r.FormValue(NextKey)
}
if next == "" {
return next
}
if qnext, err := url.QueryUnescape(next); err == nil {
if !strings.HasPrefix(qnext, "/") {
return ""
}
return qnext
}
if !strings.HasPrefix(next, "/") {
return ""
}
return next
}
// RedirectWithNextURL redirects to another page and passes the next url param,
// (e.g. a login page). target is the target redirect page, and statusCode is
// the http code used when redirecting.
//
// Example:
// if !auth(user, passwd) {
// pt.RedirectWithNextURL(w, r, r.URL.EscapedPath(), http.StatusTemporaryRedirect)
// return
// }
func RedirectWithNextURL(w http.ResponseWriter, r *http.Request, target string, statusCode int) {
http.Redirect(w, r, target+"?"+NextKey+"="+url.QueryEscape(GetNextURL(r)), statusCode)
}
// RedirectToNextURL redirects to the url specified within the "next" query
// parameter. Do this after the task (e.g. after authenticating).
//
// Example:
// if auth(user, passwd) {
// pt.RedirectToNextURL(w, r, http.StatusTemporaryRedirect)
// return
// }
func RedirectToNextURL(w http.ResponseWriter, r *http.Request, statusCode int) {
http.Redirect(w, r, GetNextURL(r), statusCode)
}