2016-02-25 120 views
-1

當我想渲染包含js文件上的腳本鏈接的html文件時,出現錯誤。 但是當我加載頁面我得到這個錯誤:加載js文件時返回404錯誤

Started GET "/views/script.js" .... Returning 404 

我的文件夾是這樣的

|--todolist 
    |--main.go 
    |--views/ 
     |--index.html 
     |--script.js 

main.go

package main 

import (
    "github.com/zenazn/goji" 
    "html/template" 
    "net/http" 
) 

func renderHTMLPage(w http.ResponseWriter, path string) { 
    t, err := template.ParseFiles(path) 
    if err != nil { 
     panic(err) 
    } 
    t.Execute(w, nil) 
} 

func Index(w http.ResponseWriter, r *http.Request) { 
    renderHTMLPage(w, "./views/index.html") 
} 

func main() { 
     goji.Get("/", Index) 
     goji.Serve() 
} 

的意見/ index.html的

<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="UTF-8"> 
    <title>Le titre du document</title> 
    </head> 
    <body> 

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    <script src="script.js"></script> 

<h1>To-Do List </h1> 
<ul id="todolist"> 
<li> Hello <button>Delete</button></li> 
<li> Wesh <button>Delete</button></li> 
</ul> 

<input type="text" id="new-text" /><button id="add">Add</button> 
    </body> 
</html> 

views/script.js

function addListItem() { 
    var text = $('#new-text').val() 
    if (text != "") { 
     $('#todolist').append('<li>'+text+'<button id="dede" name=\"' + i + '\">Delete</button></li>') 
    } 
    $('#new-text').val("") 
} 

function deleteItem() { 
    $(this).parent().remove() 
} 


$(function() { 

    $('#add').on('click', addListItem); 

    $("#todolist").on("click", "#dede", deleteItem) 

}); 

如何才能正確加載js文件?

什麼是最好的方式來創建一個應用程序誰只使用jquery/JavaScript與架構上的golang api?

謝謝

回答

1

您需要:

  • 含有/views目錄即成 - 例如goji.Get( 「/視圖/ *」,http.FileServer(http.Dir( 「/用戶/亞光/桌面/視圖/」)))`
  • 使用http.StripPrefix(推薦)

以下允許您從目錄名分離路徑:

func main() { 
    goji.Get("/views/*", http.StripPrefix("/views", http.FileServer(http.Dir("/Users/matt/Desktop/views/")))) 
    goji.Get("/", Index) 
    goji.Serve() 
} 

我建議不要從「根」的服務 - /*。更好地服務於專用資產路徑,因爲它可以在查看緩存,與CDN交互時更輕鬆。

+0

感謝您的幫助,它的工作原理! – Fantasim

0

在這種特殊情況下的代碼看起來應該像

goji.Get("/", Index) 
goji.Get("/*", http.FileServer(http.Dir("./views"))) 
goji.Serve() 

但我必須說,在保持相同的目錄模板和靜態文件是糟糕的想法,以及從根提供靜態文件。

+0

它不起作用。你會怎麼做? – Fantasim

+1

@Fantasim把所有的靜態文件放到'assets/js','assets/css'等'assets'文件夾中,並替換'goji.Get(「/ *」,http.FileServer(http.Dir(「./」 (「/ assets/*」,http.FileServer(http.Dir(「./ assets」)))''是一個好的開始。因此,您將能夠在不考慮靜態文件名與動態部分之間的衝突的情況下處理應用程序路由。 –

+0

好吧,我會盡力,謝謝:) – Fantasim