forked from mirror/gin
Added support for redirects
This commit is contained in:
parent
c3abaf9afc
commit
593de4e913
12
README.md
12
README.md
|
@ -228,7 +228,7 @@ func main() {
|
|||
}
|
||||
```
|
||||
|
||||
#### XML, and JSON rendering
|
||||
#### XML and JSON rendering
|
||||
|
||||
```go
|
||||
func main() {
|
||||
|
@ -297,6 +297,16 @@ func main() {
|
|||
}
|
||||
```
|
||||
|
||||
#### Redirects
|
||||
|
||||
Issuing a HTTP redirect is easy:
|
||||
|
||||
```r.GET("/test", func(c *gin.Context) {
|
||||
c.Redirect("http://www.google.com/", 302)
|
||||
})
|
||||
|
||||
Both internal and external locations are supported.
|
||||
```
|
||||
|
||||
#### Custom Middlewares
|
||||
|
||||
|
|
|
@ -247,6 +247,11 @@ func (c *Context) String(code int, format string, values ...interface{}) {
|
|||
c.Render(code, render.Plain, format, values)
|
||||
}
|
||||
|
||||
// Returns a 302 redirect to the specific location.
|
||||
func (c *Context) Redirect(location string, code int) {
|
||||
c.Render(302, render.Redirect, location, code)
|
||||
}
|
||||
|
||||
// Writes some data into the body stream and updates the HTTP code.
|
||||
func (c *Context) Data(code int, contentType string, data []byte) {
|
||||
if len(contentType) > 0 {
|
||||
|
|
|
@ -22,6 +22,9 @@ type (
|
|||
// Plain text
|
||||
plainRender struct{}
|
||||
|
||||
// Redirects
|
||||
redirectRender struct{}
|
||||
|
||||
// form binding
|
||||
HTMLRender struct {
|
||||
Template *template.Template
|
||||
|
@ -29,9 +32,10 @@ type (
|
|||
)
|
||||
|
||||
var (
|
||||
JSON = jsonRender{}
|
||||
XML = xmlRender{}
|
||||
Plain = plainRender{}
|
||||
JSON = jsonRender{}
|
||||
XML = xmlRender{}
|
||||
Plain = plainRender{}
|
||||
Redirect = redirectRender{}
|
||||
)
|
||||
|
||||
func writeHeader(w http.ResponseWriter, code int, contentType string) {
|
||||
|
@ -47,6 +51,12 @@ func (_ jsonRender) Render(w http.ResponseWriter, code int, data ...interface{})
|
|||
return encoder.Encode(data[0])
|
||||
}
|
||||
|
||||
func (_ redirectRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
w.Header().Set("Location", data[0].(string))
|
||||
w.WriteHeader(data[1].(int))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
||||
writeHeader(w, code, "application/xml")
|
||||
encoder := xml.NewEncoder(w)
|
||||
|
|
Loading…
Reference in New Issue