2017-04-26 59 views
-1

我有以下代碼:配菜子目錄[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

回答

2

假設你想提供的目錄上的端點/靜態的全部內容「靜態」和你運行的是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