英文:
Use root URL when using templates
问题
我感觉这是一个简单的问题,但我是一个彻头彻尾的新手,似乎找不到答案。
我正在使用以下代码根据URL路径来呈现特定的HTML模板:
func handleTemplate(w http.ResponseWriter, r *http.Request) {
templates := populateTemplates()
requestedFile := r.URL.Path[1:]
t := templates.Lookup(requestedFile + ".html")
if t != nil {
err := t.Execute(w, nil)
if err != nil {
log.Println(err)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
func main() {
http.HandleFunc("/", handleTemplate)
http.Handle("/img/", http.FileServer(http.Dir("static")))
http.Handle("/css/", http.FileServer(http.Dir("static")))
// Dev port binding
bind := fmt.Sprintf("%s:%s", "0.0.0.0", "5000")
fmt.Printf("listening on %s...", bind)
err := http.ListenAndServe(bind, nil)
if err != nil {
panic(err)
}
}
如果我有一个名为home.html的模板,那么当我浏览到localhost/home时,它会呈现给我正确的模板。
然而,我希望用户浏览到localhost/时能呈现一个特定的HTML模板。在没有框架的情况下,这是否可能?
英文:
I feel like this a simple problem, but I'm an utter noob and I cant seem to find an answer.
I'm using the following to present a specific html template based on the URL path
func handleTemplate(w http.ResponseWriter, r *http.Request) {
templates := populateTemplates()
requestedFile := r.URL.Path[1:]
t := templates.Lookup(requestedFile + ".html")
if t != nil {
err := t.Execute(w, nil)
if err != nil {
log.Println(err)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
func main() {
http.HandleFunc("/", handleTemplate)
http.Handle("/img/", http.FileServer(http.Dir("static")))
http.Handle("/css/", http.FileServer(http.Dir("static")))
// Dev port binding
bind := fmt.Sprintf("%s:%s", "0.0.0.0", "5000")
fmt.Printf("listening on %s...", bind)
err := http.ListenAndServe(bind, nil)
if err != nil {
panic(err)
}
}
So that works great if I have a template called home.html.. I can browse to localhost/home and it will present me the right template.
However I want the user to browse to localhost/ and be presented with a specific html template. Is that possible without a framework?
答案1
得分: 1
当r.URL.Path等于"/"时,渲染默认/索引/其他页面。
英文:
Sure:
if r.URL.Path == "/" {
// Render default/index/whatever page
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论