使用Golang net / http包,该任务非常容易。
您需要做的只是:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":3000", nil)
}
假定静态文件位于static
项目根目录中命名的文件夹中。
如果在folder中static
,您将进行index.html
文件调用http://localhost:3000/
,这将导致呈现该索引文件,而不是列出所有可用文件。
此外,调用该文件夹中的任何其他文件(例如http://localhost:3000/clients.html
)将显示该文件,该文件已由浏览器正确渲染(至少是Chrome,Firefox和Safari :)
更新:从不同于“ /”的网址提供文件
如果您想为文件,从文件夹说./public
下网址:localhost:3000/static
你必须使用附加功能:func StripPrefix(prefix string, h Handler) Handler
是这样的:
package main
import (
"net/http"
)
func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.ListenAndServe(":3000", nil)
}
因此,您的所有文件./public
都可以在localhost:3000/static
没有http.StripPrefix
功能,如果您尝试访问file localhost:3000/static/test.html
,服务器将在其中查找./public/static/test.html
这是因为服务器将整个URI视为文件的相对路径。
幸运的是,使用内置函数可以轻松解决该问题。
/static/
没有处理模式/static
?