使用Golang Net/Http包可以非常轻松地完成这项任务.
您需要做的就是:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":3000", nil)
}
假设静态文件位于项目根目录中名为static
的文件夹中.
如果它在文件夹static
中,您将有index.html
个文件调用http://localhost:3000/
,这将导致呈现该索引文件,而不是列出所有可用的文件.
此外,调用该文件夹中的任何其他文件(例如http://localhost:3000/clients.html
)将显示该文件,该文件由浏览器正确呈现(至少是Chrome、Firefox和Safari:)
更新:从不同于"/"的url提供文件
如果您想提供文件,比如从url:localhost:3000/static
下的文件夹./public
提供服务,您必须使用use additional function: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
函数,如果您试图访问文件localhost:3000/static/test.html
,服务器将在./public/static/test.html
中查找它
这是因为服务器将整个URI视为文件的相对路径.
幸运的是,使用内置函数可以很容易地解决这个问题.