【问题标题】:Golang gorilla mux not found handler doesn't work correctGolang gorilla mux not found 处理程序无法正常工作
【发布时间】:2016-05-06 07:39:48
【问题描述】:

我正在编写一个 Web 服务器,并且我有 Not Found Handler 函数。 登录、注册、查看页面等所有 Handle 功能均正常工作。 我也有这样的线路:router.NotFoundHandler = http.HandlerFunc(Handlers.NotFoundHandler) 处理程序是我的包,包括下一个代码:

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
    //title has to be 404.html
    title := config.Page404
    title = config.WebAppex + title

    fmt.Println("title: " + title)

    /*HERE IS QUESTION LINE*/
    r = http.NewRequest("GET", config.Page404, nil)

    fmt.Println(r.URL.Path)

    logger.Info("Sending... ", title)

    //load page
    p, err := loadPage(title)
    if err != nil {
        logger.Error("ERROR : ", err.Error())
        p, _ := loadPage(config.Page404)
        fmt.Fprintf(w, "%s", p.body) //wired way to send HTML page
        return                       //just return because of printing dry p.body
    }

    //serve it
    http.ServeFile(w, r, p.dir)
    logger.Info(p.dir, " has been sent")
}

所以问题是:如果我尝试访问 localhost:8080/nothing,那么我会得到我的漂亮 Page404 但是,如果我去 localhost:8080/nothing/nothing 或 localhost:8080/nothing/nothing/nothing 等等,我会在没有任何 CSS 的情况下得到干燥的 404.html。所以我认为问题是请求,所以我用“/404.html”的方式创建新的(它是config.Page404),但没有任何改变。我阅读了有关 gorilla mux Subrouter, bit 仅排除 localhost:8080/nothing 可能会有所帮助,但我需要所有情况。那么有什么办法可以排除所有不存在的页面呢?

UPD:我的 loadPage 函数:

func loadPage(title string) (*page, error) {
    logger.Info("Trying to load", title)
    //writing from title to body
    body, err := ioutil.ReadFile(title)
    if err != nil {
        return nil, err
    }

    return &page{dir: config.HOMEDIR + title, body: body}, nil
}

type page struct {
    dir  string
    body []byte
}

谢谢!

【问题讨论】:

    标签: go http-status-code-404 gorilla mux


    【解决方案1】:

    您可能正在使用相对 CSS 样式表路径为您的 404 页面提供服务,这在从像 /nothing/nothing/nothing 这样的嵌套页面提供服务时显然会失败。

    要么使用<base> 标签在任何地方获取绝对链接,要么将您的请求重定向到想要的页面。

    【讨论】:

    • 谢谢你,为什么我不知道基本标签你让我今晚能够入睡:)
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2014-10-23
    • 2015-04-07
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多