按照官方文档自定义的 404页面,当输入不存在的 url时候,自定义的页面可以找到,但是 浏览器展示的却是 404.tpl的源码
我的代码如下
func dbError(rw http.ResponseWriter, r *http.Request){
t,_:= template.New("dberror.html").ParseFiles(beego.BConfig.WebConfig.ViewsPath+"/dberror.html")
data :=make(map[string]interface{})
data["content"] = "database is now down"
t.Execute(rw, data)
}
func main() {
beego.ErrorHandler("dbError",dbError)
beego.Router("/", &controllers.MainController{})
beego.Run()
}
在Beego中,可以通过自定义HTTP/404页面来处理404错误。具体操作步骤如下:
创建一个新文件,例如叫做404.html,这个文件将在404页面的根目录下创建。
在404.html文件中,你可以定义一个简单的HTML页面,用于显示404错误的页面。例如:
```html
Sorry, we couldn't find the page you were looking for.
```
```html
```
```go package main
import ( "html" "net/http" )
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/404.html" { http.Error(w, "Sorry, we couldn't find the page you were looking for.", http.StatusNotFound) return }
// 在这里添加你的处理代码
})
http.ListenAndServe(":8080", nil)
} ```
这样,当你访问除404.html页面外的任何页面时,Beego都会显示404页面。