Below is my function for presenting my html templates. I've recently started work on my blog page and for some reason my first and second "else if" statements aren't being hit. :
func handleRequest(w http.ResponseWriter, r *http.Request) {
templates := populateTemplates()
// present home.html if the request url is "/"
if r.URL.Path == "/" {
t := templates.Lookup("home.html")
t.Execute(w, nil)
} else if r.URL.Path == "blog/" {
posts := getPosts()
t := template.New("blog.html")
t, _ = t.ParseFiles("blog.html")
t.Execute(w, posts)
return
} else if r.URL.Path == "blog/*" {
f := "blog/" + r.URL.Path[1:] + ".md"
fileread, _ := ioutil.ReadFile(f)
lines := strings.Split(string(fileread), "\n")
status := string(lines[0])
title := string(lines[1])
date := string(lines[2])
summary := string(lines[3])
body := strings.Join(lines[4:len(lines)], "\n")
htmlBody := template.HTML(blackfriday.MarkdownCommon([]byte(body)))
post := Post{status, title, date, summary, htmlBody, r.URL.Path[1:]}
t := template.New("_post.html")
t, _ = t.ParseFiles("_post.html")
t.Execute(w, post)
} else {
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)
}
}
}
Assuming the problem is with the blog urls, you could try this instead:
if r.URL.Path == "/" {
...
} else if r.URL.Path == "/blog" {
...
} else if strings.HasPrefix(r.URL.Path,"/blog/") {
....
} else {
I'm hoping templates.Lookup doesn't make any file system calls, presumably it just looks them up in a map.
Also, don't do this:
f := "blog/" + r.URL.Path[1:] + ".md"
fileread, _ := ioutil.ReadFile(f)
What would happen if r.URL.Path[1:] was "../mysecretfile" and you had a matching file there? It's not a good idea to use external strings without cleaning them with path.Clean or similar.