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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大