本文整理汇总了Golang中text/template.HTMLEscape函数的典型用法代码示例。如果您正苦于以下问题:Golang HTMLEscape函数的具体用法?Golang HTMLEscape怎么用?Golang HTMLEscape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了HTMLEscape函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: formatCode
func formatCode(src []byte, annotations []doc.TypeAnnotation) string {
// Collect comment positions in type annotation with Name = ""
var (
comments []doc.TypeAnnotation
s scanner.Scanner
)
fset := token.NewFileSet()
file := fset.AddFile("", fset.Base(), len(src))
s.Init(file, src, nil, scanner.ScanComments)
commentLoop:
for {
pos, tok, lit := s.Scan()
switch tok {
case token.EOF:
break commentLoop
case token.COMMENT:
p := file.Offset(pos)
comments = append(comments, doc.TypeAnnotation{Pos: p, End: p + len(lit)})
}
}
// Merge type annotations and comments without modifying the caller's slice
// of annoations.
switch {
case len(comments) == 0:
// nothing to do
case len(annotations) == 0:
annotations = comments
default:
annotations = append(comments, annotations...)
sort.Sort(sortByPos(annotations))
}
var buf bytes.Buffer
last := 0
for _, a := range annotations {
template.HTMLEscape(&buf, src[last:a.Pos])
if a.Name != "" {
p := a.ImportPath
if p != "" {
p = "/" + p
}
buf.WriteString(`<a href="`)
buf.WriteString(urlFn(p))
buf.WriteByte('#')
buf.WriteString(urlFn(a.Name))
buf.WriteString(`">`)
template.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</a>`)
} else {
buf.WriteString(`<span class="com">`)
template.HTMLEscape(&buf, src[a.Pos:a.End])
buf.WriteString(`</span>`)
}
last = a.End
}
template.HTMLEscape(&buf, src[last:])
return buf.String()
}
示例2: selectionTag
func selectionTag(w io.Writer, text []byte, selections int) {
if selections < len(startTags) {
if tag := startTags[selections]; len(tag) > 0 {
w.Write(tag)
template.HTMLEscape(w, text)
w.Write(endTag)
return
}
}
template.HTMLEscape(w, text)
}
示例3: pathEscFmt
func pathEscFmt(w io.Writer, format string, x ...interface{}) {
switch v := x[0].(type) {
case []byte:
template.HTMLEscape(w, v)
case string:
template.HTMLEscape(w, []byte(filepath.ToSlash(v)))
default:
var buf bytes.Buffer
fmt.Fprint(&buf, x)
template.HTMLEscape(w, buf.Bytes())
}
}
示例4: htmlEscFmt
func htmlEscFmt(w io.Writer, format string, x ...interface{}) {
switch v := x[0].(type) {
case int:
template.HTMLEscape(w, []byte(strconv.Itoa(v)))
case []byte:
template.HTMLEscape(w, v)
case string:
template.HTMLEscape(w, []byte(v))
default:
var buf bytes.Buffer
fmt.Fprint(&buf, x)
template.HTMLEscape(w, buf.Bytes())
}
}
示例5: Print
func (p HTMLPrinter) Print(w io.Writer, kind syntaxhighlight.Kind, tokText string) error {
class := HTMLConfig(p)[kind]
if class != "" {
_, err := w.Write([]byte(`<span class="`))
if err != nil {
return err
}
_, err = io.WriteString(w, class)
if err != nil {
return err
}
io.WriteString(w, " input-block") // For "display: block;" style.
_, err = w.Write([]byte(`">`))
if err != nil {
return err
}
}
template.HTMLEscape(w, []byte(tokText))
if class != "" {
_, err := w.Write([]byte(`</span>`))
if err != nil {
return err
}
}
return nil
}
示例6: Print
func (p HTMLPrinter) Print(w io.Writer, kind Kind, tokText string) error {
class := ((HTMLConfig)(p)).class(kind)
if class != "" {
_, err := w.Write([]byte(`<span class="`))
if err != nil {
return err
}
_, err = io.WriteString(w, class)
if err != nil {
return err
}
_, err = w.Write([]byte(`">`))
if err != nil {
return err
}
}
template.HTMLEscape(w, []byte(tokText))
if class != "" {
_, err := w.Write([]byte(`</span>`))
if err != nil {
return err
}
}
return nil
}
示例7: login
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //获取请求的方法
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, token)
} else {
//请求的是登陆数据,那么执行登陆的逻辑判断
r.ParseForm()
token := r.Form.Get("token")
fmt.Println(token)
if token != "" {
fmt.Println("***************************")
//验证token的合法性
} else {
fmt.Println("============================")
//不存在token报错
}
fmt.Println("username length:", len(r.Form["username"][0]))
fmt.Println("username:", template.HTMLEscapeString(r.Form.Get("username"))) //输出到服务器端
fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
template.HTMLEscape(w, []byte(r.Form.Get("username"))) //输出到客户端
}
}
示例8: posLink_urlFunc
func posLink_urlFunc(node ast.Node, fset *token.FileSet) string {
var relpath string
var line int
var low, high int // selection
if p := node.Pos(); p.IsValid() {
pos := fset.Position(p)
relpath = pos.Filename
line = pos.Line
low = pos.Offset
}
if p := node.End(); p.IsValid() {
high = fset.Position(p).Offset
}
var buf bytes.Buffer
template.HTMLEscape(&buf, []byte(relpath))
// selection ranges are of form "s=low:high"
if low < high {
fmt.Fprintf(&buf, "?s=%d:%d", low, high) // no need for URL escaping
// if we have a selection, position the page
// such that the selection is a bit below the top
line -= 10
if line < 1 {
line = 1
}
}
// line id's in html-printed source are of the
// form "L%d" where %d stands for the line number
if line > 0 {
fmt.Fprintf(&buf, "#L%d", line) // no need for URL escaping
}
return buf.String()
}
示例9: login
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) //get request method
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, token)
} else {
// log in request
r.ParseForm()
token := r.Form.Get("token")
if token != "" {
fmt.Println("Token: ", token)
// check token validity
} else {
// give error if no token
}
fmt.Println("username length:", len(r.Form["username"][0]))
fmt.Println("username:", template.HTMLEscapeString(r.Form.Get("username"))) // print in server side
fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
template.HTMLEscape(w, []byte(r.Form.Get("username"))) // respond to client
}
}
示例10: prettySource
func prettySource(filename string, source string, limit int) (code string, err error) {
prettyCode, ok := Print(filename, source)
if ok != nil { // If it fails to parse, just serve it raw.
coll := new(bytes.Buffer)
template.HTMLEscape(coll, []byte(source))
prettyCode = coll.String()
}
linesPre := Pre().Attrs(As{"class": "line-numbers"})
codePre := Pre().Attrs(As{"class": "code-lines"})
stopped := false
for i, code := range strings.SplitN(prettyCode, "\n", -1) {
line := i + 1
linesPre.Append(
fmt.Sprintf(
A("%d").Attrs(As{
"rel": "#L%d",
"href": "#LC%d",
"id": "LID%d",
}).Out()+"\n",
line, line, line, line))
codePre.Append(
Div(code).Attrs(As{
"class": "line",
"id": "LC" + fmt.Sprint(line),
}).Out())
if limit != 0 && i == limit {
stopped = true
break
}
}
if stopped {
linesPre.Append("\n")
codePre.Append(
Div(
"\n",
A("...").Attrs(As{
"href": fmt.Sprintf("/view/%s", filename),
"class": "go-comment",
})).Attrs(As{
"class": "line",
}).Out())
}
code = Table(
Tbody(
Tr(
Td(linesPre).Attrs(As{"width": "1%", "valign": "top"}),
Td(codePre).Attrs(As{"valign": "top"})))).Attrs(As{
"class": "code",
"cellspacing": "0",
"cellpadding": "0",
}).Out()
return
}
示例11: emphasize
// Emphasize and escape a line of text for HTML. URLs are converted into links;
// if the URL also appears in the words map, the link is taken from the map (if
// the corresponding map value is the empty string, the URL is not converted
// into a link). Go identifiers that appear in the words map are italicized; if
// the corresponding map value is not the empty string, it is considered a URL
// and the word is converted into a link. If nice is set, the remaining text's
// appearance is improved where it makes sense (e.g., `` is turned into “
// and '' into ”).
func emphasize(w io.Writer, line string, words map[string]string, nice bool) {
for {
m := matchRx.FindStringSubmatchIndex(line)
if m == nil {
break
}
// m >= 6 (two parenthesized sub-regexps in matchRx, 1st one is urlRx)
// write text before match
commentEscape(w, line[0:m[0]], nice)
// adjust match if necessary
match := line[m[0]:m[1]]
if n := pairedParensPrefixLen(match); n < len(match) {
// match contains unpaired parentheses (rare);
// redo matching with shortened line for correct indices
m = matchRx.FindStringSubmatchIndex(line[:m[0]+n])
match = match[:n]
}
// analyze match
url := ""
italics := false
if words != nil {
url, italics = words[match]
}
if m[2] >= 0 {
// match against first parenthesized sub-regexp; must be match against urlRx
if !italics {
// no alternative URL in words list, use match instead
url = match
}
italics = false // don't italicize URLs
}
// write match
if len(url) > 0 {
w.Write(html_a)
template.HTMLEscape(w, []byte(url))
w.Write(html_aq)
}
if italics {
w.Write(html_i)
}
commentEscape(w, match, nice)
if italics {
w.Write(html_endi)
}
if len(url) > 0 {
w.Write(html_enda)
}
// advance
line = line[m[1]:]
}
commentEscape(w, line, nice)
}
示例12: commentEscape
// Escape comment text for HTML. If nice is set,
// also turn `` into “ and '' into ”.
func commentEscape(w io.Writer, text string, nice bool) {
last := 0
if nice {
for i := 0; i < len(text)-1; i++ {
ch := text[i]
if ch == text[i+1] && (ch == '`' || ch == '\'') {
template.HTMLEscape(w, []byte(text[last:i]))
last = i + 2
switch ch {
case '`':
w.Write(ldquo)
case '\'':
w.Write(rdquo)
}
i++ // loop will add one more
}
}
}
template.HTMLEscape(w, []byte(text[last:]))
}
示例13: codewalkFileprint
// codewalkFileprint serves requests with ?fileprint=f&lo=lo&hi=hi.
// The filename f has already been retrieved and is passed as an argument.
// Lo and hi are the numbers of the first and last line to highlight
// in the response. This format is used for the middle window pane
// of the codewalk pages. It is a separate iframe and does not get
// the usual godoc HTML wrapper.
func codewalkFileprint(w http.ResponseWriter, r *http.Request, f string) {
abspath := f
data, err := vfs.ReadFile(fs, abspath)
if err != nil {
log.Print(err)
pres.ServeError(w, r, f, err)
return
}
lo, _ := strconv.Atoi(r.FormValue("lo"))
hi, _ := strconv.Atoi(r.FormValue("hi"))
if hi < lo {
hi = lo
}
lo = lineToByte(data, lo)
hi = lineToByte(data, hi+1)
// Put the mark 4 lines before lo, so that the iframe
// shows a few lines of context before the highlighted
// section.
n := 4
mark := lo
for ; mark > 0 && n > 0; mark-- {
if data[mark-1] == '\n' {
if n--; n == 0 {
break
}
}
}
io.WriteString(w, `<style type="text/css">@import "/doc/codewalk/codewalk.css";</style><pre>`)
template.HTMLEscape(w, data[0:mark])
io.WriteString(w, "<a name='mark'></a>")
template.HTMLEscape(w, data[mark:lo])
if lo < hi {
io.WriteString(w, "<div class='codewalkhighlight'>")
template.HTMLEscape(w, data[lo:hi])
io.WriteString(w, "</div>")
}
template.HTMLEscape(w, data[hi:])
io.WriteString(w, "</pre>")
}
示例14: ExampleAnnotate
func ExampleAnnotate() {
src := []byte(`package main
import "fmt"
func main() {
fmt.Println("Hey there, Go.")
}
`)
// debugAnnotator implements syntaxhighlight.Annotator and prints the parameters it's given.
p := debugAnnotator{Annotator: syntaxhighlight.HTMLAnnotator(syntaxhighlight.DefaultHTMLConfig)}
anns, err := highlight_go.Annotate(src, p)
if err != nil {
log.Fatalln(err)
}
sort.Sort(anns)
b, err := annotate.Annotate(src, anns, func(w io.Writer, b []byte) { template.HTMLEscape(w, b) })
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(b))
// Output:
// Annotate(0, syntaxhighlight.Keyword, "package")
// Annotate(8, syntaxhighlight.Plaintext, "main")
// Annotate(14, syntaxhighlight.Keyword, "import")
// Annotate(21, syntaxhighlight.String, "\"fmt\"")
// Annotate(28, syntaxhighlight.Keyword, "func")
// Annotate(33, syntaxhighlight.Plaintext, "main")
// Annotate(37, syntaxhighlight.Plaintext, "(")
// Annotate(38, syntaxhighlight.Plaintext, ")")
// Annotate(40, syntaxhighlight.Plaintext, "{")
// Annotate(43, syntaxhighlight.Plaintext, "fmt")
// Annotate(46, syntaxhighlight.Plaintext, ".")
// Annotate(47, syntaxhighlight.Plaintext, "Println")
// Annotate(54, syntaxhighlight.Plaintext, "(")
// Annotate(55, syntaxhighlight.String, "\"Hey there, Go.\"")
// Annotate(71, syntaxhighlight.Plaintext, ")")
// Annotate(73, syntaxhighlight.Plaintext, "}")
// <span class="kwd">package</span> <span class="pln">main</span>
//
// <span class="kwd">import</span> <span class="str">"fmt"</span>
//
// <span class="kwd">func</span> <span class="pln">main</span><span class="pln">(</span><span class="pln">)</span> <span class="pln">{</span>
// <span class="pln">fmt</span><span class="pln">.</span><span class="pln">Println</span><span class="pln">(</span><span class="str">"Hey there, Go."</span><span class="pln">)</span>
// <span class="pln">}</span>
}
示例15: declFmt
// declFmt formats a Decl as HTML.
func declFmt(decl doc.Decl) string {
var buf bytes.Buffer
last := 0
t := []byte(decl.Text)
for _, a := range decl.Annotations {
p := a.ImportPath
if p != "" {
p = "/" + p
}
template.HTMLEscape(&buf, t[last:a.Pos])
//buf.WriteString(`<a href="`)
//buf.WriteString(urlFmt(p))
//buf.WriteByte('#')
//buf.WriteString(urlFmt(a.Name))
//buf.WriteString(`">`)
template.HTMLEscape(&buf, t[a.Pos:a.End])
//buf.WriteString(`</a>`)
last = a.End
}
template.HTMLEscape(&buf, t[last:])
return buf.String()
}