【问题标题】:Fileserver returns 404 for all filesFileserver 为所有文件返回 404
【发布时间】:2017-12-05 14:47:57
【问题描述】:

因此,每当我尝试访问我的静态子目录中的任何文件时,我只会得到一个 404,未找到,访问 Home/ 另一方面工作正常,但我从主文件调用的图片很简单坏了:(,所以我想知道要更改什么,以便我可以同时提供文件和重定向我的根目录。

我的路径结构:

root/
->html
->static
->entry.go

我在这里看到了其他线程,他们都建议我执行 r.PathPrefix("/").Handler(...),但是这样做会使访问静态之外的任何文件返回 NIL,包括我的 html位于我项目根目录中的单独 html 文件中的文件,此外,重定向到其中任何一个都会返回 404,未找到。

代码如下:

package main

import (
  "fmt"
  "net/http"
  "html/template"
  "github.com/gorilla/mux"
  "os"
)

func IfError(err error, quit bool) {
  if err != nil {
    fmt.Println(err.Error())
    if(quit) {
      os.Exit(1);
    }
  }
}

func NotFound(w http.ResponseWriter, r *http.Request) {
  w.WriteHeader(404)
  t, _ := template.ParseFiles("html/404")
  err := t.Execute(w, nil)
  IfError(err, false)
}

func Home(w http.ResponseWriter, r *http.Request) {
  t, _ := template.ParseFiles("html/home")
  err := t.Execute(w, nil)
  IfError(err, false)
}

func RedirectRoot(servefile http.Handler) http.Handler {
  return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
    if r.URL.Path == "/" {
      redirect := r.URL.Host+"/home"
      http.Redirect(w, r, redirect, http.StatusSeeOther)
    } else {
      servefile.ServeHTTP(w, r)
    }
  })
}

func main()  {
  r := mux.NewRouter()
  ServeFiles := http.StripPrefix("/", http.FileServer(http.Dir("static/")))
  r.Handle("/", RedirectRoot(ServeFiles))
  r.HandleFunc("/home", Home)
  r.NotFoundHandler = http.HandlerFunc(NotFound)

  fmt.Printf("Listening ...")
  IfError(http.ListenAndServe(":8081", r), true)
}

非常感谢

【问题讨论】:

    标签: go webserver http-status-code-404 fileserver


    【解决方案1】:

    我在您的代码中看到的问题

    r.Handle("/", RedirectRoot(ServeFiles))
    

    它会匹配每条路线,可能会产生意想不到的结果。相反,清晰明确地映射您的路线,然后它将按您的预期工作。

    例如: 让我们映射负责的处理程序。这种方法基于您的目录结构。

    它只会通过文件服务器暴露static目录,其余文件和根目录是安全的。

    func main()  {
       r := mux.NewRouter()
       r.Handle("/static/", http.StripPrefix("/static/",    http.FileServer(http.Dir("static"))))
       r.HandleFunc("/home", Home)
       r.NotFoundHandler = http.HandlerFunc(NotFound)
    
       fmt.Printf("Listening ...")
       IfError(http.ListenAndServe(":8081", r), true)
    }
    

    RedirectRoot 可能不需要您的目的。

    现在,/static/*http.FileServer 服务,/homeHome 处理。


    编辑:

    如评论中所述。要将根/ 映射到主处理器和/favicon.ico,除了上面的代码sn-p 之外,还要添加以下内容。

    func favIcon(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/favicon.ico")
    } 
    
    r.HandleFunc("/favicon.ico", favIcon)
    r.HandleFunc("/", Home)
    

    favicon.ico 来自 static 目录。

    【讨论】:

    • 但是我希望我的根目录重定向到 home/,使用您的实施访问该网站会给我一个 404,未找到,并且 favicon.ico 也不会加载
    • 在答案中添加了更多详细信息,请查看。
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2015-08-31
    • 2022-01-23
    • 2012-12-20
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多