2014-07-27 95 views
2

我正在嘗試使用GO顯示靜態頁面。GO:服務靜態頁面

GO:

package main 

import "net/http" 

func main() { 
    fs := http.FileServer(http.Dir("static/home")) 
    http.Handle("/", fs) 
    http.ListenAndServe(":4747", nil) 
} 

目錄:

Project 
    /static 
     home.html 
     edit.html 
    project.go 

當我運行它,網頁顯示的鏈接來edit.html和home.html的,而不是從家庭顯示靜態頁面。 HTML。我究竟做錯了什麼。這是提供文件的最佳方式嗎?我知道還有其他的方式,例如。從HTML /模板包,但我不知道有什麼區別和何時使用這些方法。謝謝!

+0

http://stackoverflow.com/q/14086063/6309有幫助嗎? – VonC

回答

2
func main() { 
    http.Handle("/", http.FileServer(http.Dir("static"))) 
    http.ListenAndServe(":4747", nil) 
} 

你不需要static/home,只需要static

FileServer正在使用directory listing並且由於您沒有在/static中的index.html,所以會顯示目錄內容。

快速解決方法是將home.html重命名爲index.html。這將允許您訪問index.htmlhttp://localhost:4747/edit.htmlhttp://localhost:4747/edit.html。如果您只需要提供靜態文件,則不需要使用html/template

但是一個乾淨的解決方案取決於你實際上想要做什麼。

1

如果你只想寫一個簡單的靜態內容服務器,而不僅僅是一個學習體驗,我會看看馬蒂尼(http://martini.codegangsta.io/)。

典型的馬提尼應用從一個名爲「公共」文件夾中提供靜態文件是:

package main 

import (
    "github.com/go-martini/martini" 
) 

func main() { 
    m := martini.Classic() 
    m.Run() 
} 

到所謂的「靜態」一個新的靜態文件夾添加到靜態文件夾列表中搜索內容也簡單:

package main 

import (
    "github.com/go-martini/martini" 
) 

func main() { 
    m := martini.Classic() 
    m.Use(martini.Static("static")) // serve from the "static" directory as well 
    m.Run() 
} 

尼提供了很多更多的功能,以及,如會議,模板渲染,路由處理程序等..

我們USI ng Martini在這裏生產,並且對它很滿意,並且它周圍的基礎設施。

+0

謝謝!馬提尼與大猩猩相比如何? – AUL