配菜子目录[GoLang]

问题描述:

我有以下代码:配菜子目录[GoLang]

r := mux.NewRouter() 
r.Handle("/", http.FileServer(http.Dir("./frontend/build/"))) 
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/"))) 
r.PathPrefix("/api").Handler(auth) 

/api被认为是安全的。如果用户点击/,我希望他们查看PROJECTDIR/frontend目录中的index.html

的前端目录看起来从/static

frontend 
    /build 
     index.html 
     /static 
      /js 
      /css 
      /media 

中的index.html加载所有内容。不管我怎么配置这个,当我访问localhost:3000时,我可以得到index.html,但是在/static下的所有东西都是404'd。

我怎么配置这个不正确?

+0

参见[此类似QA] (https://stackoverflow.com/questions/43601359/how-do-i-serve-css-and-js-in-go-lang) – putu

假设你想提供的目录上的端点/静态的全部内容“静态”和你运行的是BSD/Linux机器下面的语法应该工作:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))) 
+0

我在MacOS上(并在构建中的Heroku上运行)。假设你的意思是静态的完整路径?这不起作用。 \t r.Handle(“/”,http.FileServer(http.Dir(“frontend/build /”))) \t http.Handle(“/ static /”,http.StripPrefix(“/ static /”,http .FileServer(http.Dir(“frontend/build/static /”)))) \t r.PathPrefix(“/ api”)。Handler(auth) –

+0

http.Dir(“frontend/build/static /”)doesn没有指定正确的路径。你需要用“/”开始路径来表示你的机器的根目录(所以路径应该是/ home/myuser/myapp/static),或者用“./”来指定你正在运行的当前目录应用程序从你的路径的起点(因此,如果你从“/ home/myuser/myapp /”运行,那么“./”会被翻译成那个) – George