-
Notifications
You must be signed in to change notification settings - Fork 0
/
redirect.go
63 lines (53 loc) · 1.61 KB
/
redirect.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
package webutil
import (
"encoding/json"
"errors"
"fmt"
"html"
"net/http"
"net/url"
)
type redirectError struct {
u *url.URL
code int
}
func SendRedirect(w http.ResponseWriter, url string, code int) {
w.Header().Set("Location", url)
w.WriteHeader(code) // http.StatusFound
fmt.Fprintf(w, "You are being redirected to <a href=\"%s\">%s</a>. If you see this message, please manually follow the link.", html.EscapeString(url), html.EscapeString(url))
// try various stuff to cause the redirect to happen in case header failed to happen
if js, err := json.Marshal(url); err == nil {
fmt.Fprintf(w, "<script language=\"javascript\">window.location = %s;</script>", js)
}
fmt.Fprintf(w, "<meta http-equiv=\"Refresh\" content=\"0; url=%s\"/>", html.EscapeString(url))
fmt.Fprintf(w, "<meta http-equiv=\"Location\" content=\"%s\"/>", html.EscapeString(url))
}
// code can be one of http.StatusMovedPermanently or http.StatusFound or
// any 3xx http status code
func RedirectErrorCode(u *url.URL, code int) error {
// generate a redirect error
n := &redirectError{u: new(url.URL), code: code}
// copy url
*n.u = *u
return n
}
func RedirectError(u *url.URL) error {
// generate a redirect error
n := &redirectError{u: new(url.URL), code: http.StatusFound}
// copy url
*n.u = *u
return n
}
func (e *redirectError) Error() string {
return fmt.Sprintf("Redirect required to %s", e.u)
}
func (e *redirectError) ServeHTTP(w http.ResponseWriter, req *http.Request) {
SendRedirect(w, e.u.String(), e.code)
}
func IsRedirect(e error) http.Handler {
var r *redirectError
if errors.As(e, &r) {
return r
}
return nil
}