因此,无论何时我尝试访问我的静态子目录中的任何文件,我只会得到一个404,Not Found,Accessing Home /另一方面工作得很好,但是我打电话给我的图片从主文件简直是坏:(,所以我想知道要改变什么,这样我可以提供文件服务,并在同一时间重定向我的根目录Fileserver对所有文件返回404
我的道路结构:
root/
->html
->static
->entry.go
我看到这里的其他线程,他们都建议我做r.PathPrefix(“/”)。Handler(...),但这样做使得它访问任何文件之外的静态返回NIL,包括我的HTML文件在我的项目的根目录中有一个单独的html文件,而且,重定向到它们中的任何一个都会返回404,Not Found。
下面的代码:
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)
}
非常感谢您
但我想我的根目录重定向到home /,访问网站与您的imlementation会给我一个404,未找到,并favicon.ico将不会加载 – Whiteclaws
添加更多详细信息的答案,请有看看。 – jeevatkm