2017-08-08 24 views
0

我覺得這是一個簡單的問題,但我是一個完全noob,我似乎無法找到答案。使用模板時使用根URL

我使用下列基於URL路徑

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的那個偉大工程上提出具體的HTML模板..我可以瀏覽到本地主機/家它會給我提供正確的模板。

但是我希望用戶瀏覽到本地主機/並提供一個特定的html模板。沒有框架可能嗎?

回答

1

肯定的:

if r.URL.Path == "/" { 
    // Render default/index/whatever page 
} 
+0

真棒,謝謝。 – FishFenly