-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredirect.go
95 lines (79 loc) · 2.11 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
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
package htadaptor
import (
"fmt"
"net/http"
)
var (
_ Encoder = (*temporaryRedirectEncoder)(nil)
_ Encoder = (*permanentRedirectEncoder)(nil)
)
type temporaryRedirectEncoder struct{}
// NewTemporaryRedirectEncoder redirects the HTTP client
// to the location returned by a domain call
// using [http.StatusTemporaryRedirect] status.
//
// If domain call does not return a string, returns an error.
func NewTemporaryRedirectEncoder() Encoder {
return &temporaryRedirectEncoder{}
}
func (t *temporaryRedirectEncoder) ContentType() string {
return "text/html"
}
func (t *temporaryRedirectEncoder) Encode(
w http.ResponseWriter,
r *http.Request,
code int,
v any,
) error {
location, ok := v.(string)
if !ok {
return fmt.Errorf("redirection encoder received \"%T\" value instead of a string", v)
}
http.Redirect(w, r, location, http.StatusTemporaryRedirect)
return nil
}
type permanentRedirectEncoder struct{}
// NewPermanentRedirectEncoder redirects the HTTP client
// to the location returned by a domain call
// using [http.StatusPermanentRedirect] status.
//
// If domain call does not return a string, returns an error.
func NewPermanentRedirectEncoder() Encoder {
return &permanentRedirectEncoder{}
}
func (t *permanentRedirectEncoder) ContentType() string {
return "text/html"
}
func (t *permanentRedirectEncoder) Encode(
w http.ResponseWriter,
r *http.Request,
code int,
v any,
) error {
location, ok := v.(string)
if !ok {
return fmt.Errorf("redirection encoder received \"%T\" value instead of a string", v)
}
http.Redirect(w, r, location, http.StatusPermanentRedirect)
return nil
}
type temporaryRedirect string
func (t temporaryRedirect) ServeHTTP(
w http.ResponseWriter,
r *http.Request,
) {
http.Redirect(w, r, string(t), http.StatusTemporaryRedirect)
}
func NewTemporaryRedirect(to string) http.Handler {
return temporaryRedirect(to)
}
type permanentRedirect string
func (p permanentRedirect) ServeHTTP(
w http.ResponseWriter,
r *http.Request,
) {
http.Redirect(w, r, string(p), http.StatusPermanentRedirect)
}
func NewPermanentRedirect(to string) http.Handler {
return permanentRedirect(to)
}