gpt4 book ai didi

golang 中的 HTML 模板

转载 作者:IT王子 更新时间:2023-10-29 01:36:51 26 4
gpt4 key购买 nike

我正在学习本教程: golang tutorial - wiki除了“其他任务”部分中的最后一点,我已经设法使所有内容正常工作。我对教程的实现:

package main

import (
"fmt"
"io/ioutil"
"net/http"
"html/template"
"regexp"
)

type Page struct {
Title string
Body []byte
}

func (p *Page) save() error {
filename := "data/" + p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}

func loadPage(title string) (*Page, error) {
filename := "data/" + title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, _ := template.ParseFiles("template/" + tmpl + ".html");
t.Execute(w, p)
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/" + title, http.StatusFound);
return
}
expr := regexp.MustCompile(`\[.+\]`)
p.Body = expr.ReplaceAllFunc(p.Body, func ( match []byte) []byte {
return []byte("<a href='/view/" + string(match) + "'>" + string(match) + "</a>")
})
renderTemplate(w, "view", p);
}

func saveHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/save/"):]
body := r.FormValue("body")
p := &Page{Title: title, Body: []byte(body)}
p.save()
http.Redirect(w, r, "/view/" + title, http.StatusFound)
}

func editHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/edit/"):]
p, err := loadPage(title);

if err != nil {
p = &Page{Title: title}
}
renderTemplate(w, "edit", p);
}

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/view/index", http.StatusFound)
})
http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/edit/", editHandler)
http.HandleFunc("/save/", saveHandler)
http.ListenAndServe(":8080", nil)
fmt.Println("Running");
}

html/template 引擎按预期打印 anchor 标记,但使用 html 实体将其转义。我一直没能找到合适的方法。

最佳答案

使用template.HTML将正文标记为安全 HTML。

以下函数将正文转换为 HTML。

// Move to package-level variable so that it's compile once.
var linkPat = regexp.MustCompile(`\[.+\]`)

func toHTML(s string) template.HTML {

// Escape everything in the string first to ensure that
// special characters ('<' for example) are displayed as
// characters and not treated as markup.
s = template.HTMLEscapeString(s)

// Insert the links.
s = linkPat.ReplaceAllStringFunc(s, func(m string) string {
s = s[1 : len(s)-1]
return "<a href='/view/" + m + "'>" + m + "</a>"
})

return template.HTML(s)
}

渲染页面使用:

renderTemplate(w, "edit", map[string]interface{}{
"Title": p.Body,
"Body": toHTML(p.Body),
})

关于golang 中的 HTML 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com