当前位置: 首页>>代码示例>>Golang>>正文


Golang template.HTMLEscape函数代码示例

本文整理汇总了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()
}
开发者ID:nvcnvn,项目名称:gopkgdoc,代码行数:60,代码来源:template.go

示例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)
}
开发者ID:qunhu,项目名称:go_src_comment,代码行数:11,代码来源:format.go

示例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())
	}
}
开发者ID:RavenZZ,项目名称:liteide,代码行数:12,代码来源:godocdir.go

示例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())
	}
}
开发者ID:RavenZZ,项目名称:liteide,代码行数:14,代码来源:godocdir.go

示例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
}
开发者ID:tobstarr,项目名称:tobstarr.com,代码行数:26,代码来源:main.go

示例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
}
开发者ID:rechen,项目名称:wharf,代码行数:25,代码来源:highlight.go

示例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"))) //输出到客户端
	}
}
开发者ID:pokerG,项目名称:GoBeginner,代码行数:29,代码来源:upload.go

示例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()
}
开发者ID:tw4452852,项目名称:go-src,代码行数:35,代码来源:godoc.go

示例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
	}
}
开发者ID:espang,项目名称:examples,代码行数:26,代码来源:server.go

示例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
}
开发者ID:vito,项目名称:go-play,代码行数:59,代码来源:pretty.go

示例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 &ldquo;
// and '' into &rdquo;).
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)
}
开发者ID:Greentor,项目名称:go,代码行数:65,代码来源:comment.go

示例12: commentEscape

// Escape comment text for HTML. If nice is set,
// also turn `` into &ldquo; and '' into &rdquo;.
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:]))
}
开发者ID:Lao16,项目名称:gcc,代码行数:22,代码来源:comment.go

示例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>")
}
开发者ID:iolg,项目名称:golangdoc,代码行数:47,代码来源:codewalk.go

示例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">&#34;fmt&#34;</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">&#34;Hey there, Go.&#34;</span><span class="pln">)</span>
	// <span class="pln">}</span>
}
开发者ID:parsnips,项目名称:snips,代码行数:52,代码来源:main_test.go

示例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()
}
开发者ID:wangmingjob,项目名称:site,代码行数:23,代码来源:template.go


注:本文中的text/template.HTMLEscape函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。