go - 文件服务器为所有文件返回 404

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

所以每当我尝试访问我的静态子目录中的任何文件时,我只会得到一个 404,未找到,另一方面,访问 Home/工作得很好,但是我从 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)
}

非常感谢

最佳答案

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

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 处理。


编辑:

如评论中所问。要将根 / 映射到 home 处理程序和 /favicon.ico,请在上面的代码片段中添加以下内容。

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

r.HandleFunc("/favicon.ico", favIcon)
r.HandleFunc("/", Home)

favicon.icostatic 目录提供。

关于go - 文件服务器为所有文件返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44866837/

相关文章:

c# - 如何向 tcp 服务器发出 http 请求?

java - Spring应用程序对第​​三方应用程序上的所有URL请求(除了/)返回404(在本地主机上工作正常)

google-app-engine - angularjs html5mode刷新页面获取404

node.js - 如何检查网站是否有自定义 404 页面或默认页面?

Golang 与 GORM。如何正确地将模型类型传递到方法中?

gometalinter/errcheck 在延迟返回变量的函数时返回警告

javascript - golang 中的 pubsub 替代方案

戈朗 : fatal error: unexpected signal during runtime execution

nodemcu esp8266 中的 CORS 问题

php - .php 网址到 .html 网址