Beego: Cannot return JSON with non-200 status code

Created on 13 Jun 2015  ·  4Comments  ·  Source: astaxie/beego

When the status code is explicitly set, the Content-Type header is automatically change to text/plain. I would like the ability to send back JSON data for API consistency.

func (u *UserController) Post() {
    u.Ctx.ResponseWriter.WriteHeader(500)
    u.Data["json"] = map[string]string{"error": "A user with that username already exists"}
    fmt.Println(err)
    u.ServeJson()
}

The response looks correct at first glance, it is formatted as a JSON object, but the Content-Type header is set to text/plain, limiting its ability to be used correctly.

Most helpful comment

func (u *UserController) GetAll() {
    users := models.GetAllUsers()
    u.Ctx.Output.SetStatus(300)
    u.Data["json"] = users
    u.ServeJson()
}

qq20150613-1

All 4 comments

func (u *UserController) GetAll() {
    users := models.GetAllUsers()
    u.Ctx.Output.SetStatus(300)
    u.Data["json"] = users
    u.ServeJson()
}

qq20150613-1

Thank you. What is the purpose of the Controller.Ctx.ResponseWriter.WriteHeader function if the Controller.Ctx.Output.SetStatus works with no side effects?

Controller.Ctx.ResponseWriter.WriteHeader will directly write to the client,

while Controller.Ctx.Output.SetStatus will cache the status until output the content

Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bysph picture bysph  ·  6Comments

astaxie picture astaxie  ·  4Comments

drmaples picture drmaples  ·  6Comments

kaushiksriram100 picture kaushiksriram100  ·  3Comments

flycash picture flycash  ·  3Comments