英文:
Golang serving html files
问题
我有一些HTML文件在文件夹/html中(例如main.html,page1.html,page2.html等)。我使用下面的Go代码来提供这些文件:
r := mux.NewRouter()
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(htmlDir))))
所以如果我打开地址http://127.0.0.1/page1.html,那么page1.html将会显示(这是我需要的)。
但是我还想将地址http://127.0.0.1/绑定到main.html。我该如何做呢?
我可以将main.html重命名为index.html,但我认为这不是正确的方法。
英文:
I have some html files in folder /html (for example main.html,page1.html, page2.html,etc ). And I serve it, using next Go code
r := mux.NewRouter()
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(htmlDir))))
So if I open address http://127.0.0.1/page1.html, then page1.html will be shown( it is what I need).
But I also want to bind address http://127.0.0.1/ to main.html. How can I do it?
I can rename main.html to index.html, but I think it is not true way.
答案1
得分: 2
你可以额外添加一个HandlerFunc
来处理这个问题:
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(htmlDir))))
在homeHandler
函数中,你可以提供你想要提供的文件:
func homeHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("./%s/index.htm", htmlDir))
}
可能还有其他选项...
英文:
You could additionally add a HandlerFunc
to handle that:
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir(htmlDir))))
In the homeHandler you serve the file you want to serve:
func homeHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, fmt.Sprintf("./%s/index.htm", htmlDir))
}
There might be other options...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论