在使用模板时,请使用根URL。

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

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
}

huangapple
  • 本文由 发表于 2017年8月8日 22:39:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/45571318.html
匿名

发表评论

匿名网友

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

确定