-2

I am using Golang to write web applications, and I use beego framework. It seems the the framework have the internal status code returned for golang web server.

I am wondering is there any method in golang or beego, or other tools that can let me control the status code returned to browser, say 200, or 500 or others number.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Peter Hon
  • 321
  • 2
  • 6
  • 10

4 Answers4

6

In your controller you can access the http.ResponseWriter via the Ctx

type SomeController struct {
    beego.Controller
}

func (c *SomeController) Get() {
    c.Ctx.ResponseWriter.WriteHeader(500)
}

Edit: After further inspection you should probably do this:

func (c *SomeController) Get() {
    c.CustomAbort(500, "Internal server error")
}

I'm leaving the reference about the context because you can find the http.Request and http.ResponseWriter on controller's Ctx property.

Community
  • 1
  • 1
jmaloney
  • 11,580
  • 2
  • 36
  • 29
1

Have a look on http.ResponseWriter.WriteHeader. If you have access to the ResponseWriter-object, you can easily return your own HTTP status code.

fls0815
  • 483
  • 4
  • 9
1
c.Abort("500")

it response HTTP code is 200.

Must be:

c.Ctx.ResponseWriter.WriteHeader(500)    
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
ken
  • 199
  • 1
  • 11
-1

Very late to the party. I m able to set status on beego v2.0.2.

func (u *UserController) Post() {
    var user models.User
    json.Unmarshal(u.Ctx.Input.RequestBody, &user)
    uid, _ := models.AddUser(&user)
    u.Data["json"] = map[string]interface{}{"uid": uid}
    u.Ctx.Output.Status = http.StatusCreated #<<<------------
    u.ServeJSON()
}
Netro
  • 7,119
  • 6
  • 40
  • 58