使用模板时使用根URL

时间:2017-08-08 14:39:29

标签: go

我觉得这是一个简单的问题,但我是一个彻头彻尾的菜鸟,我似乎无法找到答案。

我使用以下内容根据网址路径提供特定的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模板。没有框架可能吗?

1 个答案:

答案 0 :(得分:1)

不确定

if r.URL.Path == "/" {
    // Render default/index/whatever page
}
相关问题