2017-07-02 56 views
0

因此,无论何时我尝试访问我的静态子目录中的任何文件,我只会得到一个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) 
} 

非常感谢您

回答

0

我看到的问题在你的代码

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,请在以上代码片段中添加以下内容。

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服务目录。

+0

但我想我的根目录重定向到home /,访问网站与您的imlementation会给我一个404,未找到,并favicon.ico将不会加载 – Whiteclaws

+0

添加更多详细信息的答案,请有看看。 – jeevatkm