beego自定义404、401、403、500、503等页面

beego 框架默认支持 404、401、403、500、503 这几种错误的处理。用户可以自定义相应的错误处理,从1.4.3版本开始,支持Controller方式定义Error错误处理函数:

step1;在main方法在加入

beego.ErrorController(&controllers.ErrorController{})

在这里插入图片描述
step2:新建一个Error控制器

 package controllers

import "github.com/astaxie/beego"
/**
  该控制器处理页面错误请求
 */
type ErrorController struct {
	beego.Controller
}
func (c *ErrorController) Error401() {
	c.Data["content"] = "未经授权,请求要求验证身份"
	c.TplName="error/401.tpl"
}
func (c *ErrorController) Error403() {
	c.Data["content"] = "服务器拒绝请求"
	c.TplName="error/403.tpl"
}
func (c *ErrorController) Error404() {
	c.Data["content"] = "很抱歉您访问的地址或者方法不存在"
	c.TplName="error/404.tpl"
}

func (c *ErrorController) Error500() {
	c.Data["content"] = "server error"
	c.TplName = "error/500.tpl"
}
func (c *ErrorController) Error503() {
	c.Data["content"] = "服务器目前无法使用(由于超载或停机维护)"
	c.TplName = "error/503.tpl"
}

step3: 在views新建一个error目录,并在目录添加对应文件,这里以404页面为主

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>404</title>
      <style type="text/css">
          body.error_page
          {
              background-color: #00629f;
              background-image: url(https://lxxybucket.oss-cn-hangzhou.aliyuncs.com/EXILE/error.png);
              background-position: center top;
              background-repeat: no-repeat;
          }
          #error
          {
              color: #FFF;
              width: 100%;
              text-align: center;
              margin: 22% auto;
          }
          #error span,#error a
          {
              color:Yellow;
          }
          #error a:hover
          {
              color:#FFF;
              text-decoration: underline;
              cursor: pointer;
          }
         .error_number{
             font-size: 8rem;
         }
      </style>

</head>
<body class="error_page">
<h1 id="error">
    <span>{{.content}}</span>

</h1>
</body>
</html>
<script>
    window.onload=function () {
        $width=document.body.clientWidth;
        if($width>1024){
            document.getElementById("error").style.margin="22% auto";
        }else{
            document.getElementById("error").style.margin="42% auto";
        }
    }
</script>

step4:实际运行beego项目进行访问测试
在这里插入图片描述
大功告成

发布了77 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u014265398/article/details/90312112
今日推荐