Beego生产环境回来状态码的bug

Beego生产环境返回状态码的bug

项目用的是Beego的1.4.2。但是最近发现cdn会把项目中的40x或者50x的页面缓存住。

研究了下Beego的源码,然后经过测试后发现,在生产环境下,当请求的页面出错时,返回的页面的状态码40x或者50x会被统一改为200。

这个是因为开发者谢大将写入response的状态码的那行给注释了。

要是用Beego的同僚注意了,这个地方得自己处理下。

如下处理即可:

在main.go中:

package main

import (
	"github.com/astaxie/beego"
	"zhe800h5wap/controllers"
	_ "zhe800h5wap/routers"
)

func main() {
	beego.Errorhandler("400", controllers.PageNotFound)
	beego.Errorhandler("401", controllers.PageNotFound)
	beego.Errorhandler("403", controllers.PageNotFound)
	beego.Errorhandler("404", controllers.PageNotFound)
	beego.Errorhandler("405", controllers.PageNotFound)
	beego.Errorhandler("500", controllers.ServerError)
	beego.Errorhandler("502", controllers.ServerError)
	beego.Errorhandler("503", controllers.ServerError)
	beego.Errorhandler("504", controllers.ServerError)
	beego.Run()
}

其中,beego.Errorhandler("400", controllers.PageNotFound) 会处理页面状态码是400的,其他的依次类推。

在controllers包中:

在init.go中新增:

func PageNotFound(rw http.ResponseWriter, r *http.Request) {
	rw.WriteHeader(http.StatusNotFound)
}

func ServerError(rw http.ResponseWriter, r *http.Request) {
	rw.WriteHeader(http.StatusInternalServerError)
}
其中,对应的controllers的方法会将40x和50x的状态码统一处理为404和500。

这样处理后,cdn就不会缓存这些状态码不是200的页面了。


fang,2015-02-12