2017-04-25 61 views
6

我遵循GoLang教程here,但無論出於什麼原因,我都無法讓應用程序服務於css和js。如果我運行我的靜態頁面沒有去服務器頁面的CSS工作正常。另一方面,當我運行go服務器時,css不起作用。如何在Go Lang中使用CSS和JS

這裏是我的HTML看起來有點像:

<link rel="stylesheet" href="../assets/css/bootstrap.min.css"> 
 
<link rel="stylesheet" href="../assets/css/bootstrap-theme.min.css"> 
 
<link rel="stylesheet" href="../assets/css/custom.css"> 
 

 
. 
 
. 
 
. 
 
     
 
then under the body tag 
 

 
<script src="../assets/js/jquery.min.js"></script> 
 
<script src="../assets/js/bootstrap.min.js"></script> 
 

 
. 
 
. 
 
.

我的文件樹是這個樣子

enter image description here

如何讓我的旅途中的應用程序服務的CSS和JavaScript我需要?

的問題已經被解決了,這裏是工作的主:

func main() { 
    http.HandleFunc("/view/", makeHandler(viewHandler)) 
    http.HandleFunc("/edit/", makeHandler(editHandler)) 
    http.HandleFunc("/save/", makeHandler(saveHandler)) 
    http.HandleFunc("/index/", makeHandler(indexHandler)) 


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

    http.ListenAndServe(":8080", nil) 
} 

這裏是我使用

func indexHandler(w http.ResponseWriter, r *http.Request, title string) { 
    p := &Page{Title: title} 
    err := templates.ExecuteTemplate(w, "index.html", p) 
    if err != nil { 
     http.Error(w, err.Error(), http.StatusInternalServerError) 
    } 
} 
+0

[在Go模板中包含js文件]的可能重複(http://stackoverflow.com/questions/28899675/include-js-file-in-go-template/28899786#28899786);和[使用golang webserver,網站根目錄映射到文件系統?](http://stackoverflow.com/questions/28745161/with-golang-webserver-where-does-the-root-of-the-website -map-onto-the-filesystem/28745280) – icza

回答

9

你可以成爲像靜態文件的目錄處理程序的例子所以:

http.Handle("/", http.FileServer(http.Dir("css/"))) 

將服務您的css目錄在/。當然,您可以在任何您選擇的路徑上提供任何目錄。

我可能會確保靜態路徑不妨礙其他路徑並使用類似這樣的東西。

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

目錄static在你的項目都放置你的jscss。然後這將在domain.com/static/css/filename.css和domain.com/static/js/filename.js服務於他們。

StripPrefix方法刪除前綴,因此它不會嘗試搜索例如在static/css/filename.cssstatic目錄當然是不會找到的。它會在static目錄中尋找css/filename.css,這是正確的。

+0

我應該在哪裏放置那行代碼?主要用於所有的函數處理程序,或者在我的函數中提供索引模板,例如 – bmacrevolution

+0

。通常在'http.ListenAndServe'之前。所以可能在你的主要。 – RayfenWindspear

+0

這樣做似乎並沒有奏效。我發佈了一些更新的代碼 – bmacrevolution