Go 使用模板时使用根URL
我觉得这是个简单的问题,但我是个彻头彻尾的笨蛋,似乎找不到答案 我将使用下面的代码基于URL路径呈现一个特定的html模板Go 使用模板时使用根URL,go,Go,我觉得这是个简单的问题,但我是个彻头彻尾的笨蛋,似乎找不到答案 我将使用下面的代码基于URL路径呈现一个特定的html模板 func handleTemplate(w http.ResponseWriter, r *http.Request) { templates := populateTemplates() requestedFile := r.URL.Path[1:] t := templates.Lookup(requestedFile + ".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模板。如果没有框架,这可能吗?当然可以:
if r.URL.Path == "/" {
// Render default/index/whatever page
}