php %3ca%3e链接到模板,html/template(模板)

import "html/template"

概述

索引

示例

概观

模板包(html/template)实现了数据驱动的模板,以便在代码注入过程中安全地生成HTML输出。它提供了与包文本/模板相同的接口,只要输出是HTML,就应该使用它来代替文本/模板。

这里的文档侧重于包的安全特性。有关如何自行编写模板的信息,请参阅文本/模板的文档。

介绍

该软件包包装文本/模板,以便您可以共享其模板API以安全地解析和执行HTML模板。

tmpl, err := template.New("name").Parse(...)// 错误检查已删除err = tmpl.Execute(out, data)

如果成功,tmpl 现在将是注射安全的。否则, err 是 ErrorCode 文档中定义的错误。

HTML模板将数据值视为应该被编码的纯文本,以便它们可以安全地嵌入到HTML文档中。转义是上下文的,因此操作可以出现在 JavaScript,CSS和URI 上下文中。

这个包使用的安全模型假定模板作者是可信的,而 Execute 的数据参数不是。更多细节在下面提供。

示例

import "text/template"...t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)err = t.ExecuteTemplate(out, "T", "")

产生

Hello, !

但在HTML /模板中的上下文自动转义

import "html/template"...t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)err = t.ExecuteTemplate(out, "T", "")

产生安全的、转义过的HTML输出

Hello, <script>alert('you have been pwned')</script>!

上下文

该软件包可以理解 HTML,CSS,JavaScript和URI 。它给每个简单的操作流水线增加了清理功能,所以给出了摘录

{{.}}

在解析时,每个 {{.}} 都会被覆盖,以根据需要添加转义函数。在这种情况下,它变成了

{{. | htmlescaper}}

urlescaper,attrescaper和htmlescaper 是内部转义函数的别名。

错误

有关详细信息,请参阅ErrorCode的文档。

A fuller picture

在第一次阅读时可以跳过此包评论的其余部分;它包含了解转义上下文和错误消息所需的详细信息。大多数用户不需要了解这些细节。

上下文

假设 {{.}} 是O'Reilly: How are you?,下表显示了 {{.}} 在左侧上下文中使用时的显示方式。

Context                          {{.}} After{{.}}                            O'Reilly: How are <i>you</i>?                O'Reilly: How are you?                O'Reilly: How are %3ci%3eyou%3c/i%3e?              O'Reilly%3a%20How%20are%3ci%3e...%3f             O\x27Reilly: How are \x3ci\x3eyou...?               "O\x27Reilly: How are \x3ci\x3eyou...?"     O\x27Reilly: How are \x3ci\x3eyou...\x3f

如果在不安全的上下文中使用,则可能会过滤掉该值:

Context                          {{.}} After                 #ZgotmplZ

因为“O'Reilly:”不是像“http:”这样的允许协议。

如果{{.}}是无关紧要的词left,那么它可以更广泛地出现,

Context                              {{.}} After{{.}}                                left                    left                     left                    left                left        left             left       left  left   left

非字符串值可以在JavaScript上下文中使用。如果是

struct{A,B string}{ "foo", "bar" }

在转义模板中

然后模板输出是

请参阅包 json 以了解如何封装非字符串内容以嵌入JavaScript上下文中。

键入的字符串

默认情况下,此包假定所有管道都生成纯文本字符串。它添加了必要的转义管道阶段,以便在正确的上下文中正确安全地嵌入纯文本字符串。

如果数据值不是纯文本,则可以通过使用其类型对其进行标记来确保它不会过度转义。

来自content.go的HTML,JS,URL和其他类型可以携带免于转义的安全内容。

模板

Hello, {{.}}!

可以调用

tmpl.Execute(out, template.HTML(`World`))

来生成

Hello, World!

而不是

Hello, <b>World<b>!

如果{{.}}是常规字符串,则会生成。

安全模型

https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html#problem_definition定义此包使用的“safe”。

这个包假定模板作者是可信的,Execute的数据参数不是,并试图在不受信任的数据面前保留下面的属性:

结构保留属性:“......当模板作者以安全模板语言编写HTML标记时,浏览器会将输出的相应部分解释为标记,而不管不受信任数据的值如何,对于其他结构(如属性边界和JS和CSS字符串边界。“

代码效果属性:“...只有模板作者指定的代码才能运行,因为将模板输出注入到页面中,模板作者指定的所有代码都应该运行相同的结果。”

Least Surprise Property:“熟悉HTML,CSS 和 JavaScript 的开发人员(或代码审查员),他们知道发生上下文自动转移应该能够查看{ {.}} 并正确推断出正在进行的清理。”

示例

package mainimport ("html/template""log""os")func main() {const tpl = `

html>

{{.Title}}

{{range .Items}}

{{ . }}
{{else}}
no rows
{{end}}

`

check := func(err error) {if err != nil {

log.Fatal(err)}}

t, err := template.New("webpage").Parse(tpl)check(err)

data := struct {

Title string

Items []string}{

Title: "My page",

Items: []string{"My photos","My blog",},}

err = t.Execute(os.Stdout, data)check(err)

noItems := struct {

Title string

Items []string}{

Title: "My another page",

Items: []string{},}

err = t.Execute(os.Stdout, noItems)check(err)}

示例(Autoescaping)

package mainimport ("html/template""log""os")func main() {

check := func(err error) {if err != nil {

log.Fatal(err)}}

t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)check(err)

err = t.ExecuteTemplate(os.Stdout, "T", "")check(err)}

示例(Escape)

package mainimport ("fmt""html/template""os")func main() {const s = `"Fran & Freddie's Diner" `

v := []interface{}{`"Fran & Freddie's Diner"`, ' ', ``}

fmt.Println(template.HTMLEscapeString(s))

template.HTMLEscape(os.Stdout, []byte(s))

fmt.Fprintln(os.Stdout, "")

fmt.Println(template.HTMLEscaper(v...))

fmt.Println(template.JSEscapeString(s))

template.JSEscape(os.Stdout, []byte(s))

fmt.Fprintln(os.Stdout, "")

fmt.Println(template.JSEscaper(v...))

fmt.Println(template.URLQueryEscaper(v...))}

索引

func HTMLEscape(w io.Writer, b []byte)

func HTMLEscapeString(s string) string

func HTMLEscaper(args ...interface{}) string

func IsTrue(val interface{}) (truth, ok bool)

func JSEscape(w io.Writer, b []byte)

func JSEscapeString(s string) string

func JSEscaper(args ...interface{}) string

func URLQueryEscaper(args ...interface{}) string

type CSS

type Error

func (e *Error) Error() string

type ErrorCode

type FuncMap

type HTML

type HTMLAttr

type JS

type JSStr

type Template

func Must(t *Template, err error) *Template

func New(name string) *Template

func ParseFiles(filenames ...string) (*Template, error)

func ParseGlob(pattern string) (*Template, error)

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

func (t *Template) Clone() (*Template, error)

func (t *Template) DefinedTemplates() string

func (t *Template) Delims(left, right string) *Template

func (t *Template) Execute(wr io.Writer, data interface{}) error

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

func (t *Template) Funcs(funcMap FuncMap) *Template

func (t *Template) Lookup(name string) *Template

func (t *Template) Name() string

func (t *Template) New(name string) *Template

func (t *Template) Option(opt ...string) *Template

func (t *Template) Parse(text string) (*Template, error)

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

func (t *Template) ParseGlob(pattern string) (*Template, error)

func (t *Template) Templates() []*Template

type URL

示例

Package Template (Block) Template (Glob) Template (Helpers) Template (Parsefiles) Template (Share) Package (Autoescaping) Package (Escape)

包文件

attr.go content.go context.go css.go doc.go error.go escape.go html.go js.go template.go transition.go url.go

func HTMLEscape

func HTMLEscape(w io.Writer, b []byte)

HTMLEscape 写入到明文数据 b 的转义HTML 等价物中。

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString 返回纯文本数据的转义 HTML 等价物。

func HTMLEscaper

func HTMLEscaper(args ...interface{}) string

HTMLEscaper 返回其参数文本表示的转义 HTML 等价物。

func IsTrue

func IsTrue(val interface{}) (truth, ok bool)

IsTrue报告该值是否为'true',意味着它的类型不为零,以及该值是否具有有意义的真值。这是 if 和其他此类行为所使用的真相的定义。

func JSEscape

func JSEscape(w io.Writer, b []byte)

JSEscape写入 w 的纯文本数据 b 的逃逸 JavaScript 等价物。

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString 返回纯文本数据的转义 JavaScript 等价物。

func JSEscaper

func JSEscaper(args ...interface{}) string

JSEscaper 返回其参数的文本表示的转义 JavaScript 等价物。

func URLQueryEscaper

func URLQueryEscaper(args ...interface{}) string

URLQueryEscape r 以适合于嵌入到 URL 查询中的形式返回其参数的文本表示的转义值。

type CSS

CSS封装了与以下任何匹配的已知安全内容:

1. CSS3样式表的制作,例如`p {color:purple}`。2. CSS3规则生成,例如`a [href =〜“https:”]。foo #bar`。3. CSS3声明制作,如`color:red; 保证金:2px`。4. CSS3值的产生,例如`rgba(0,0,255,127)`。

请参阅http://www.w3.org/TR/css3-syntax/#parsing和https://web.archive.org/web/20090211114933/http://w3.org/TR/css3-syntax#style

使用此类型会带来安全风险:封装内容应来自可信来源,因为它将逐字包含在模板输出中。

type CSS string

type Error

错误描述了模板转义期间遇到的问题。

type Error struct {        // ErrorCode describes the kind of error.

ErrorCode ErrorCode        // Node is the node that caused the problem, if known.        // If not nil, it overrides Name and Line.

Node parse.Node        // Name is the name of the template in which the error was encountered.

Name string        // Line is the line number of the error in the template source or 0.

Line int        // Description is a human-readable description of the problem.

Description string}

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

ErrorCode 是一种错误的代码。

type ErrorCode int

我们为转义模板时显示的每个错误定义代码,但转义模板也可能在运行时失败。

输出:“ZgotmplZ”示例:

where {{.X}} evaluates to `javascript:...`

讨论:

"ZgotmplZ" is a special value that indicates that unsafe content reached a

CSS or URL context at runtime. The output of the example will be  If the data comes from a trusted source, use content types to exempt itfrom filtering: URL(`javascript:...`).

const (        // OK indicates the lack of an error.

OK ErrorCode = iota        // ErrAmbigContext: "... appears in an ambiguous context within a URL"        // Example:        //           // Discussion:        //   {{.X}} is in an ambiguous URL context since, depending on {{.C}},        //  it may be either a URL suffix or a query parameter.        //   Moving {{.X}} into the condition removes the ambiguity:        //   

ErrAmbigContext        // ErrBadHTML: "expected space, attr name, or end of tag, but got ...",        //   "... in unquoted attr", "... in attribute name"        // Example:        //           //           //           //   

ErrBadHTML        // ErrBranchEnd: "{{if}} branches end in different contexts"        // Example:        //   {{if .C}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值