Skip to content

Commit

Permalink
Merge branch 'redirect' of https://github.com/alexandernyquist/gin in…
Browse files Browse the repository at this point in the history
…to develop
  • Loading branch information
manucorporat committed Aug 18, 2014
2 parents faf181d + 64fb835 commit ceec1b6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
12 changes: 11 additions & 1 deletion README.md
Expand Up @@ -251,7 +251,7 @@ func main() {
}
```

#### XML, and JSON rendering
#### XML and JSON rendering

```go
func main() {
Expand Down Expand Up @@ -320,6 +320,16 @@ func main() {
}
```

#### Redirects

Issuing a HTTP redirect is easy:

```r.GET("/test", func(c *gin.Context) {
c.Redirect(301, "http://www.google.com/")
})
Both internal and external locations are supported.
```

#### Custom Middlewares

Expand Down
9 changes: 9 additions & 0 deletions context.go
Expand Up @@ -247,6 +247,15 @@ func (c *Context) String(code int, format string, values ...interface{}) {
c.Render(code, render.Plain, format, values)
}

// Returns a HTTP redirect to the specific location.
func (c *Context) Redirect(code int, location string) {
if code >= 300 && code <= 308 {
c.Render(code, render.Redirect, location)
} else {
panic(fmt.Sprintf("Cannot send a redirect with status code %d", 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 {
Expand Down
16 changes: 13 additions & 3 deletions render/render.go
Expand Up @@ -22,16 +22,20 @@ type (
// Plain text
plainRender struct{}

// Redirects
redirectRender struct{}

// form binding
HTMLRender struct {
Template *template.Template
}
)

var (
JSON = jsonRender{}
XML = xmlRender{}
Plain = plainRender{}
JSON = jsonRender{}
XML = xmlRender{}
Plain = plainRender{}
Redirect = redirectRender{}
)

func writeHeader(w http.ResponseWriter, code int, contentType string) {
Expand All @@ -45,6 +49,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(code)
return nil
}

func (_ xmlRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
writeHeader(w, code, "application/xml")
encoder := xml.NewEncoder(w)
Expand Down

0 comments on commit ceec1b6

Please sign in to comment.