transport/http(feat): add redirector to forward request (#2074)
* add redirector to forward request Co-authored-by: chenzhihui <chenzhihui@bilibili.com>pull/2075/head
parent
5de1f081f6
commit
1b3529fd0b
@ -0,0 +1,18 @@ |
||||
package http |
||||
|
||||
type redirect struct { |
||||
URL string |
||||
Code int |
||||
} |
||||
|
||||
func (r *redirect) Redirect() (string, int) { |
||||
return r.URL, r.Code |
||||
} |
||||
|
||||
// NewRedirect new a redirect with url, which may be a path relative to the request path.
|
||||
// The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
|
||||
// If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body.
|
||||
// Setting the Content-Type header to any value, including nil, disables that behavior.
|
||||
func NewRedirect(url string, code int) Redirector { |
||||
return &redirect{URL: url, Code: code} |
||||
} |
@ -0,0 +1,23 @@ |
||||
package http |
||||
|
||||
import ( |
||||
"net/http/httptest" |
||||
"testing" |
||||
) |
||||
|
||||
func TestRedirect(t *testing.T) { |
||||
var ( |
||||
redirectURL = "/redirect" |
||||
redirectCode = 302 |
||||
) |
||||
r := httptest.NewRequest("POST", "/test", nil) |
||||
w := httptest.NewRecorder() |
||||
_ = DefaultResponseEncoder(w, r, NewRedirect(redirectURL, redirectCode)) |
||||
|
||||
if w.Code != redirectCode { |
||||
t.Fatalf("want %d but got %d", redirectCode, w.Code) |
||||
} |
||||
if v := w.Header().Get("Location"); v != redirectURL { |
||||
t.Fatalf("want %s but got %s", redirectURL, v) |
||||
} |
||||
} |
Loading…
Reference in new issue