英文:
Golang beego framework to set the status code
问题
我正在使用Golang编写Web应用程序,并使用beego框架。似乎该框架为Golang Web服务器返回了内部状态码。
我想知道在Golang或beego中是否有任何方法,或者其他工具可以让我控制返回给浏览器的状态码,比如200、500或其他数字。
英文:
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.
答案1
得分: 6
在你的控制器中,你可以通过Ctx
访问http.ResponseWriter
。
type SomeController struct {
beego.Controller
}
func (c *SomeController) Get() {
c.Ctx.ResponseWriter.WriteHeader(500)
}
编辑:经过进一步检查,你可能应该这样做:
func (c *SomeController) Get() {
c.CustomAbort(500, "Internal server error")
}
我保留关于上下文的参考,因为你可以在控制器的Ctx
属性中找到http.Request
和http.ResponseWriter
。
英文:
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.
答案2
得分: 1
请查看http.ResponseWriter.WriteHeader
。如果你可以访问ResponseWriter
对象,你可以轻松地返回自己的HTTP状态码。
英文:
Have a look on http.ResponseWriter.WriteHeader
. If you have access to the ResponseWriter
-object, you can easily return your own HTTP status code.
答案3
得分: 1
c.Abort("500")
它响应的HTTP代码是200。
必须是:
c.Ctx.ResponseWriter.WriteHeader(500)
英文:
c.Abort("500")
it response HTTP code is 200.
Must be:
c.Ctx.ResponseWriter.WriteHeader(500)
答案4
得分: -1
非常晚才加入。我能够在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()
}
英文:
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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论