Golang提供HTML文件的方法

huangapple go评论152阅读模式
英文:

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...

huangapple
  • 本文由 发表于 2017年7月12日 17:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45054471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定