【发布时间】: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