Skip to content

Commit 71684e3

Browse files
committed
feat(transport/http): support redirect errors in default error encoder
1 parent fb8e43e commit 71684e3

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

transport/http/codec.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,11 @@ func DefaultResponseEncoder(w http.ResponseWriter, r *http.Request, v any) error
105105

106106
// DefaultErrorEncoder encodes the error to the HTTP response.
107107
func DefaultErrorEncoder(w http.ResponseWriter, r *http.Request, err error) {
108+
if rd, ok := err.(Redirector); ok {
109+
url, code := rd.Redirect()
110+
http.Redirect(w, r, url, code)
111+
return
112+
}
108113
se := errors.FromError(err)
109114
codec, _ := CodecForRequest(r, "Accept")
110115
body, err := codec.Marshal(se)

transport/http/redirect.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package http
22

3+
var (
4+
_ error = (*redirect)(nil)
5+
_ Redirector = (*redirect)(nil)
6+
)
7+
38
type redirect struct {
49
URL string
510
Code int
@@ -9,6 +14,10 @@ func (r *redirect) Redirect() (string, int) {
914
return r.URL, r.Code
1015
}
1116

17+
func (r *redirect) Error() string {
18+
return "redirect to " + r.URL
19+
}
20+
1221
// NewRedirect new a redirect with url, which may be a path relative to the request path.
1322
// The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
1423
// If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body.

0 commit comments

Comments
 (0)