Golang beego框架设置状态码

huangapple go评论72阅读模式
英文:

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.Requesthttp.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, &amp;user)
	uid, _ := models.AddUser(&amp;user)
	u.Data[&quot;json&quot;] = map[string]interface{}{&quot;uid&quot;: uid}
	u.Ctx.Output.Status = http.StatusCreated #&lt;&lt;&lt;------------
	u.ServeJSON()
}

huangapple
  • 本文由 发表于 2014年9月25日 18:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/26035962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定