duanbei2914 2017-10-05 15:51
浏览 5
已采纳

为什么我的URL.Path语句没有被点击

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), "
")
        status := string(lines[0])
        title := string(lines[1])
        date := string(lines[2])
        summary := string(lines[3])
        body := strings.Join(lines[4:len(lines)], "
")
        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)
        }
    }
}
  • 写回答

1条回答 默认 最新

  • douhuan4699 2017-10-05 17:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分