2017-04-21 12:26:41 +00:00
|
|
|
package response
|
|
|
|
|
|
|
|
import (
|
|
|
|
beecontext "github.com/astaxie/beego/context"
|
|
|
|
)
|
|
|
|
|
2017-04-30 16:28:26 +00:00
|
|
|
// JSON renders value to the response as JSON
|
|
|
|
func JSON(value interface{}, encoding ...bool) Renderer {
|
2017-04-21 12:26:41 +00:00
|
|
|
return rendererFunc(func(ctx *beecontext.Context) {
|
|
|
|
var (
|
|
|
|
hasIndent = true
|
|
|
|
hasEncoding = false
|
|
|
|
)
|
|
|
|
//TODO: need access to BConfig :(
|
|
|
|
// if BConfig.RunMode == PROD {
|
|
|
|
// hasIndent = false
|
|
|
|
// }
|
|
|
|
if len(encoding) > 0 && encoding[0] {
|
|
|
|
hasEncoding = true
|
|
|
|
}
|
|
|
|
ctx.Output.JSON(value, hasIndent, hasEncoding)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-04-22 22:33:50 +00:00
|
|
|
func errorRenderer(err error) Renderer {
|
2017-04-21 12:26:41 +00:00
|
|
|
return rendererFunc(func(ctx *beecontext.Context) {
|
|
|
|
ctx.Output.SetStatus(500)
|
|
|
|
ctx.WriteString(err.Error())
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-04-30 16:28:26 +00:00
|
|
|
// Redirect renders http 302 with a URL
|
|
|
|
func Redirect(localurl string) Renderer {
|
2017-04-22 22:33:50 +00:00
|
|
|
return statusCodeWithRender{302, func(ctx *beecontext.Context) {
|
|
|
|
ctx.Redirect(302, localurl)
|
|
|
|
}}
|
|
|
|
}
|
|
|
|
|
2017-04-30 16:28:26 +00:00
|
|
|
// RenderMethodResult renders the return value of a controller method to the output
|
2017-04-21 12:26:41 +00:00
|
|
|
func RenderMethodResult(result interface{}, ctx *beecontext.Context) {
|
|
|
|
if result != nil {
|
|
|
|
renderer, ok := result.(Renderer)
|
|
|
|
if !ok {
|
|
|
|
err, ok := result.(error)
|
|
|
|
if ok {
|
2017-04-22 22:33:50 +00:00
|
|
|
renderer = errorRenderer(err)
|
2017-04-21 12:26:41 +00:00
|
|
|
} else {
|
2017-04-30 16:28:26 +00:00
|
|
|
renderer = JSON(result)
|
2017-04-21 12:26:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
renderer.Render(ctx)
|
|
|
|
}
|
|
|
|
}
|