如何使用go web服务器提供静态html文件? [英] How do you serve a static html file using a go web server?
问题描述
如何使用go web服务器为index.html(或其他静态HTML文件)提供服务?
How do you serve index.html (or some other static HTML file) using a go web server?
我只想要一个基本的静态HTML文件(如例如一篇文章),我可以从网页服务器提供服务。 HTML应该可以在go程序之外修改,因为它在使用HTML模板的情况下是可行的。
I just want a basic, static HTML file (like an article, for example) which I can serve from a go web server. The HTML should be modifiable outside of the go program, as it would be in the case while using HTML templates.
这是我的web服务器,它只托管硬编码的文本(Hello world!)。
This is my web server which only hosts hard-coded text ("Hello world!").
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello world!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
推荐答案
与Golang净/ http包。
That task is very easy with Golang net/http package.
所有您需要做的是:
All You need to do is:
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":3000", nil)
}
假设静态文件位于文件夹na中med static
在项目的根目录中。
assuming that static files are in folder named static
in the root directory of the project.
如果它位于文件夹 static
,你将有 index.html
文件调用 http:// localhost:3000 /
这将导致呈现该索引文件,而不是列出所有可用的文件。
If it's in folder static
, you'll have index.html
file calling http://localhost:3000/
which will result in rendering that index file instead of listing all the files availible.
另外,调用该文件夹中的任何其他文件(例如 http :// localhost:3000 / clients.html
)将显示该文件,由浏览器正确呈现(至少Chrome,Firefox和Safari))
Additionally, calling any other file in that folder (for example http://localhost:3000/clients.html
) will show that file, properly rendered by the browser (at least Chrome, Firefox and Safari :))
如果您要提供文件,请从文件夹 ./ public
在url下: localhost:3000 / static
您必须使用附加函数: func StripPrefix前缀字符串,h Handler)Handler
像这样:
If You want to serve files, say from folder ./public
under url: localhost:3000/static
You have to use additional function: func StripPrefix(prefix string, h Handler) Handler
like this:
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
Thanks to that, all your files from ./public
are avalible under localhost:3000/static
下得到 http.StripPrefix
函数,如果您尝试访问文件 localhost:3000 / static / test.html
,服务器会在<$ c $中查找它c> ./ public / static / test.html
Without http.StripPrefix
function, if you would try to access file localhost:3000/static/test.html
, the server would look for it in ./public/static/test.html
这是因为服务器将整个URI视为文件的相对路径。
This is because the server treats the whole URI as a relative path to the file.
幸运的是,使用内置函数很容易解决问题。
Fortunately, it's easily solved with the built-in function.
这篇关于如何使用go web服务器提供静态html文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!