Пример #1
0
func (h *Handler) StoreMessage(c web.C, w http.ResponseWriter, r *http.Request) {
	room := r.PostFormValue("room")
	if room == "" {
		fmt.Fprintf(w, response.New().WithError(errors.New("No room specified. Skipping.")).Json())
		return
	}

	msg := map[string]interface{}{
		"room":    html.EscapeString(r.PostFormValue("room")),
		"author":  html.EscapeString(r.PostFormValue("author")),
		"message": html.EscapeString(r.PostFormValue("message")),
		"at":      serializer.ParseJavaScriptTime(r.PostFormValue("time")),
	}

	logForReq(c, fmt.Sprintf("Inserting %s", msg))

	message, err := h.DB.InsertMessage(msg)

	if err != nil {
		errMsg := fmt.Sprintf("Could not insert message %s: %s", msg, err.Error())
		http.Error(w, response.New().WithError(errors.New(errMsg)).Json(), 500)
		return
	}
	fmt.Fprintf(w, response.New().WithMessage(message).Json())
}
Пример #2
0
func (HTMLFormatter) Format(element Element) string {
	switch el := element.(type) {
	case *Document:
		return `<!DOCTYPE html>
<html>
<head>
` + HTML.documentHeader(el) + `
</head>
<body>
<div class="container">
<h1 class="page-header">` + html.EscapeString(el.Title) + `</h1>
` + HTML.formatContent(el.Contents()) + `
</div>
<script src="/js/bootstrap.js" async></script>
</body>
</html>`
	case *Italic:
		return "<em>" + HTML.formatContent(el.Contents()) + "</em>"
	case *Bold:
		return "<strong>" + HTML.formatContent(el.Contents()) + "</strong>"
	case *LineBreak:
		return "<br>"
	case *Paragraph:
		return "<p>" + HTML.formatContent(el.Contents()) + "</p>"
	case *Image:
		return "<img src=\"" + html.EscapeString(el.URL) + "\" alt=\"" + html.EscapeString(el.Description) + "\" title=\"" + html.EscapeString(el.Description) + "\">"
	case *Link:
		return "<a href=\"" + html.EscapeString(el.URL) + "\">" + HTML.formatContent(el.Contents()) + "</a>"
	case *LeafElement:
		return html.EscapeString(el.Text)
	case *Article:
		return "<article><h1>" + el.Title + " <small>" + el.Timestamp.Format("15:04 2 Jan 2006") + "</small></h1>\n" + HTML.formatContent(el.Contents()) + "</article>"
	}
	return fmt.Sprintf("%#v", element)
}
func getPackageNodes(goCode []ParsedCode) (packageNodes []graph.PackageNode) {

	packagesMap := make(map[string]*graph.PackageNode)

	//Map the files to their graph.PackageNode
	for _, parsedCode := range goCode {

		//Get packageNode from map
		nodePtr := packagesMap[parsedCode.PackageName()]
		if nodePtr == nil {
			node := graph.CreatePackageNode(
				html.EscapeString(parsedCode.PackageName()),
				html.EscapeString(parsedCode.PackagePath()),
				nil)
			nodePtr = &node
		}

		//add row
		nodePtr.AddPackageNodeRow(graph.CreatePackageNodeRow(
			html.EscapeString(parsedCode.FileName()),
			htmlEscapeStringArray(parsedCode.Functions()),
			htmlEscapeStringArray(parsedCode.Types()),
			htmlEscapeStringArray(parsedCode.Variables())))

		//put back in map
		packagesMap[parsedCode.PackageName()] = nodePtr
	}

	//Take the graph.PackageNode out of the map and put in an array.
	for _, packageNode := range packagesMap {
		packageNodes = append(packageNodes, *packageNode)
	}

	return packageNodes
}
Пример #4
0
func (sh *SyncHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	sh.lk.Lock()
	defer sh.lk.Unlock()

	fmt.Fprintf(rw, "<h1>%s to %s Sync Status</h1><p><b>Current status: </b>%s</p>",
		sh.fromName, sh.toName, html.EscapeString(sh.status))

	fmt.Fprintf(rw, "<h2>Stats:</h2><ul>")
	fmt.Fprintf(rw, "<li>Blobs copied: %d</li>", sh.totalCopies)
	fmt.Fprintf(rw, "<li>Bytes copied: %d</li>", sh.totalCopyBytes)
	if !sh.recentCopyTime.IsZero() {
		fmt.Fprintf(rw, "<li>Most recent copy: %s</li>", sh.recentCopyTime.Format(time.RFC3339))
	}
	fmt.Fprintf(rw, "<li>Copy errors: %d</li>", sh.totalErrors)
	fmt.Fprintf(rw, "</ul>")

	if len(sh.blobStatus) > 0 {
		fmt.Fprintf(rw, "<h2>Current Copies:</h2><ul>")
		for blobstr, sfn := range sh.blobStatus {
			fmt.Fprintf(rw, "<li>%s: %s</li>\n",
				blobstr, html.EscapeString(sfn.String()))
		}
		fmt.Fprintf(rw, "</ul>")
	}

	if len(sh.recentErrors) > 0 {
		fmt.Fprintf(rw, "<h2>Recent Errors:</h2><ul>")
		for _, te := range sh.recentErrors {
			fmt.Fprintf(rw, "<li>%s: %s</li>\n",
				te.t.Format(time.RFC3339),
				html.EscapeString(te.err.Error()))
		}
		fmt.Fprintf(rw, "</ul>")
	}
}
Пример #5
0
// HTTP handler for _dump
func (h *handler) handleDump() error {
	viewName := h.PathVar("view")
	base.LogTo("HTTP", "Dump view %q", viewName)
	opts := db.Body{"stale": false, "reduce": false}
	result, err := h.db.Bucket.View(db.DesignDocSyncGateway, viewName, opts)
	if err != nil {
		return err
	}
	title := fmt.Sprintf("/%s: “%s” View", html.EscapeString(h.db.Name), html.EscapeString(viewName))
	h.setHeader("Content-Type", `text/html; charset="UTF-8"`)
	h.response.Write([]byte(fmt.Sprintf(
		`<!DOCTYPE html><html><head><title>%s</title></head><body>
		<h1>%s</h1><code>
		<table border=1>
		`,
		title, title)))
	h.response.Write([]byte("\t<tr><th>Key</th><th>Value</th><th>ID</th></tr>\n"))
	for _, row := range result.Rows {
		key, _ := json.Marshal(row.Key)
		value, _ := json.Marshal(row.Value)
		h.response.Write([]byte(fmt.Sprintf("\t<tr><td>%s</td><td>%s</td><td><em>%s</em></td>",
			html.EscapeString(string(key)), html.EscapeString(string(value)), html.EscapeString(row.ID))))
		h.response.Write([]byte("</tr>\n"))
	}
	h.response.Write([]byte("</table>\n</code></html></body>"))
	return nil
}
Пример #6
0
func (pr *publishRequest) serveHTTP() {
	if !pr.rootpn.Valid() {
		pr.rw.WriteHeader(404)
		return
	}

	if pr.Debug() {
		pr.rw.Header().Set("Content-Type", "text/html")
		pr.pf("I am publish handler at base %q, serving root %q (permanode=%s), suffix %q, subreq %q<hr>",
			pr.base, pr.ph.RootName, pr.rootpn, html.EscapeString(pr.suffix), html.EscapeString(pr.subres))
	}

	if err := pr.findSubject(); err != nil {
		if err == os.ErrNotExist {
			pr.rw.WriteHeader(404)
			return
		}
		log.Printf("Error looking up %s/%q: %v", pr.rootpn, pr.suffix, err)
		pr.rw.WriteHeader(500)
		return
	}

	if pr.Debug() {
		pr.pf("<p><b>Subject:</b> <a href='/ui/?p=%s'>%s</a></p>", pr.subject, pr.subject)
		return
	}

	switch pr.SubresourceType() {
	case "":
		pr.serveSubjectTemplate()
	case "b":
		// TODO: download a raw blob
	case "f": // file download
		pr.serveSubresFileDownload()
	case "i": // image, scaled
		pr.serveSubresImage()
	case "s": // static
		pr.req.URL.Path = pr.subres[len("/=s"):]
		if len(pr.req.URL.Path) <= 1 {
			http.Error(pr.rw, "Illegal URL.", http.StatusNotFound)
			return
		}
		file := pr.req.URL.Path[1:]
		if m := closurePattern.FindStringSubmatch(file); m != nil {
			pr.req.URL.Path = "/" + m[1]
			pr.ph.closureHandler.ServeHTTP(pr.rw, pr.req)
			return
		}
		if file == "deps.js" {
			serveDepsJS(pr.rw, pr.req, pr.ph.uiDir)
			return
		}
		serveStaticFile(pr.rw, pr.req, uistatic.Files, file)
	case "z":
		pr.serveZip()
	default:
		pr.rw.WriteHeader(400)
		pr.pf("<p>Invalid or unsupported resource request.</p>")
	}
}
Пример #7
0
func nodeTable(name string, urls []string) string {
	// escape name
	name = html.EscapeString(name)

	// turn big things like 'how do we eat bananas' into 'how ... bananas'
	nameshow := name
	if len(name) > 45 {
		nameshow = name[:28] + " ... " + name[len(name)-12:]
	}

	// escape urls
	for i := range urls {
		urls[i] = html.EscapeString(urls[i])
	}

	table := fmt.Sprintf("<<table tooltip=\"%s\" border=\"0\" cellborder=\"0\" cellpadding=\"4\">", name)
	table += fmt.Sprintf("<tr><td bgcolor=\"black\" align=\"center\"><font color=\"white\"><b> %s </b></font></td></tr>", nameshow)
	for _, url := range urls {
		// remove url endings on show
		urlshow := url
		if len(urlshow) > 45 {
			urlshow = urlshow[:42] + "..."
		}
		table += fmt.Sprintf("<tr><td href=\"%s\" target=\"_blank\" tooltip=\"%s\">%s</td></tr>", url, url, url[7:])
	}
	table += "</table>>"
	return table
}
Пример #8
0
//line _test\conents.ego:1
func MyContents(w io.Writer, u *User) error {
//line _test\conents.ego:2
	_, _ = fmt.Fprint(w, "\n\n")
//line _test\conents.ego:4
	_, _ = fmt.Fprint(w, "\n\n    <h1>Hello ")
//line _test\conents.ego:5
	_, _ = fmt.Fprint(w, html.EscapeString(fmt.Sprintf("%v", strings.TrimSpace(u.FirstName))))
//line _test\conents.ego:5
	_, _ = fmt.Fprint(w, "!</h1>\n\n    <p>Here's a list of your favorite colors:</p>\n    <ul>\n      ")
//line _test\conents.ego:9
	for _, colorName := range u.FavoriteColors {
//line _test\conents.ego:10
		_, _ = fmt.Fprint(w, "\n        <li>")
//line _test\conents.ego:10
		_, _ = fmt.Fprint(w, html.EscapeString(fmt.Sprintf("%v", colorName)))
//line _test\conents.ego:10
		_, _ = fmt.Fprint(w, "</li>\n      ")
//line _test\conents.ego:11
	}
//line _test\conents.ego:12
	_, _ = fmt.Fprint(w, "\n    </ul>\n\n")
//line _test\conents.ego:14
	EgoLayout(w, MyLayout)
//line _test\conents.ego:15
	_, _ = fmt.Fprint(w, "\n")
	return nil
}
Пример #9
0
func (node *tagOptionNode) Execute(ctx *p2.ExecutionContext, writer p2.TemplateWriter) *p2.Error {
	fieldObj := ctx.Public[node.field]
	if nil == fieldObj {
		return ctx.Error("field '"+node.field+"' is missing.", nil)
	}
	field, _ := fieldObj.(*revel.Field)
	if nil == field {
		return ctx.Error(fmt.Sprintf("field '"+node.field+"' isn't Field - %T.", fieldObj), nil)
	}

	val, err := node.value.Evaluate(ctx)
	if err != nil {
		return err
	}
	val_str := val.String()

	selected := ""
	if field.Flash() == val_str || (field.Flash() == "" && field.Value() == val_str) {
		selected = " selected"
	}

	fmt.Fprintf(writer, `<option value="%s"%s>%s</option>`,
		html.EscapeString(val_str), selected, html.EscapeString(node.label))
	return nil
}
Пример #10
0
func escHtml(s string) string {
	ns := ""
	noesc := false
	w := ""
	for _, r := range s {
		switch {
		case r == 1:
			noesc = true
			if w != "" {
				ns += html.EscapeString(w)
				w = ""
			}
			continue
		case r == 2:
			noesc = false
			continue
		case noesc:
			ns += string(r)
		default:
			w += string(r)
		}
	}
	if w != "" {
		ns += html.EscapeString(w)
	}
	return ns
}
Пример #11
0
func handlerLeader(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
	fmt.Fprintf(w, "trying to set leader \n")
	s := r.URL.Path
	fmt.Fprintf(w, "\n\n", s, " \n\n")
	x := html.EscapeString(r.URL.Path)
	fmt.Fprintf(w, "\n x => ", x, " \n")
	parts1 := strings.Split(s, "%")
	for k1, v1 := range parts1 {
		fmt.Fprintf(w, "\n k=", k1, ",v=", v1)
	}
	//fmt.Fprintf(w, parts[1]," \n")

	u, err := url.Parse(s)
	if err != nil {
		fmt.Fprintf(w, "error receiving parameters, "+err.Error())
	} else {
		//fmt.Fprintf(w, "raw: ",u.RawQuery)
		parts := strings.Split(u.Path, "/")
		for k, v := range parts {
			fmt.Fprintf(w, "\n k=", k, ",v=", v)
		}
		/*
			  if len(parts) != 2 {
					fmt.Fprintf(w, "usage: setleader/ip-of-the-leader")
				} else {
					leaderIP := parts[1]
					fmt.Fprintf(w, "leader = ",leaderIP)
				}
		*/
	}
}
Пример #12
0
func markupById(id, text string) string {
	color := generateRandomColorFromId(id)
	format := "<span foreground=\"%s\">%s</span>"
	return fmt.Sprintf(format,
		html.EscapeString(color),
		html.EscapeString(text))
}
Пример #13
0
Файл: ego.go Проект: vycb/egotpl
//line home.ego:1
func Home(w io.Writer, p *Page) error {
//line home.ego:2
	_, _ = io.WriteString(w, "\n\n")
//line home.ego:3
	Header(w, p)
//line home.ego:4
	_, _ = io.WriteString(w, "\n<h1>Hello ")
//line home.ego:4
	_, _ = io.WriteString(w, html.EscapeString(fmt.Sprintf("%v", p.Title)))
//line home.ego:4
	_, _ = io.WriteString(w, "</h1>\n\n<p>Here's a list of your favorite colors:</p>\n\n<ul>\n\t")
//line home.ego:9
	for _, colorName := range p.FavoriteColors {
//line home.ego:10
		_, _ = io.WriteString(w, "\n\t<li>")
//line home.ego:10
		_, _ = io.WriteString(w, html.EscapeString(fmt.Sprintf("%v", colorName)))
//line home.ego:10
		_, _ = io.WriteString(w, "</li>\n\t")
//line home.ego:11
	}
//line home.ego:12
	_, _ = io.WriteString(w, "\n</ul>\n")
//line home.ego:13
	Footer(w, p)
//line home.ego:14
	_, _ = io.WriteString(w, "\n")
	return nil
}
Пример #14
0
func writeBrowsePage(w http.ResponseWriter, r *http.Request, diskSpace string, breadcrumbName []string, breadcrumbLink []string, listing []*pathEntry, uploadUrl string) {
	shtml := assetAsString("static/index.html")
	pathPart := assetAsString("static/path.htmlpart")

	breadcrumbHtml := ""
	for i, bn := range breadcrumbName {
		bn = html.EscapeString(bn)
		bl := html.EscapeString(breadcrumbLink[i])

		if i < len(breadcrumbName)-1 {
			breadcrumbHtml += "	    <li><a href='" + bl + "'>" + bn + "</a></li>"
		} else {
			breadcrumbHtml += "	    <li class='active'><a href='" + bl + "'>" + bn + "</a></li>"
		}
	}

	pathHtml := ""
	for _, path := range listing {
		pp := strings.Replace(pathPart, "$PATH_LINK", path.pathLink, 1)
		pp = strings.Replace(pp, "$PATH_ICON", path.pathIcon, 1)
		pp = strings.Replace(pp, "$PATH_NAME", path.pathName, 1)
		pp = strings.Replace(pp, "$FILE_SIZE", path.fileSize, 1)
		pathHtml += pp
	}

	shtml = strings.Replace(shtml, "$DISK_SPACE", diskSpace, 1)
	shtml = strings.Replace(shtml, "$BREADCRUMB", breadcrumbHtml, 1)
	shtml = strings.Replace(shtml, "$DIRECTORY_LISTING", pathHtml, 1)
	shtml = strings.Replace(shtml, "$UPLOAD_URL", uploadUrl, 1)
	shtml = strings.Replace(shtml, "$PUBLIC_URL", public_url, 10)

	fmt.Fprint(w, shtml)
}
Пример #15
0
func formatline(line string) (markup string) {
	line = strings.Trim(line, "\t\r\n ")
	if len(line) > 0 {
		if strings.HasPrefix(line, ">") && !(strings.HasPrefix(line, ">>") && re_backlink.MatchString(strings.Split(line, " ")[0])) {
			// le ebin meme arrows
			markup += "<p><span class='memearrows'>"
			markup += html.EscapeString(line)
			markup += "</span></p>"
		} else if strings.HasPrefix(line, "==") && strings.HasSuffix(line, "==") {
			// redtext
			markup += "<p><span class='redtext'>"
			markup += html.EscapeString(line[2 : len(line)-2])
			markup += "</span></p>"
		} else {
			// regular line
			markup += "<p>"
			// for each word
			for _, word := range strings.Split(line, " ") {
				// check for backlink
				if re_backlink.MatchString(word) {
					markup += backlink(word)
				} else {
					// linkify as needed
					word = html.EscapeString(word)
					markup += xurls.Strict.ReplaceAllString(word, `<a href="$1">$1</a>`)
				}
				markup += " "
			}
			markup += "</p>"
		}
	}
	return
}
Пример #16
0
//line web/frontend/views/expenses_list.ego:1
func writeExpensesList(w io.Writer, v *ExpensesList) error {
//line web/frontend/views/expenses_list.ego:2
	_, _ = io.WriteString(w, "\n\n<h1>Expenses</h1>\n\n")
//line web/frontend/views/expenses_list.ego:5
	for _, e := range v.Expenses {
//line web/frontend/views/expenses_list.ego:6
		_, _ = io.WriteString(w, "\n<div>\n    ")
//line web/frontend/views/expenses_list.ego:7
		_, _ = io.WriteString(w, html.EscapeString(fmt.Sprintf("%v", e.Description)))
//line web/frontend/views/expenses_list.ego:7
		_, _ = io.WriteString(w, " - ")
//line web/frontend/views/expenses_list.ego:7
		_, _ = io.WriteString(w, html.EscapeString(fmt.Sprintf("%v", e.Amount)))
//line web/frontend/views/expenses_list.ego:8
		_, _ = io.WriteString(w, "\n</div>\n")
//line web/frontend/views/expenses_list.ego:9
	}
//line web/frontend/views/expenses_list.ego:10
	_, _ = io.WriteString(w, "\n\n<h1>New Expense</h1>\n\n")
//line web/frontend/views/expenses_list.ego:13
	new(ExpenseForm).Render(w)
//line web/frontend/views/expenses_list.ego:14
	_, _ = io.WriteString(w, "\n")
	return nil
}
Пример #17
0
func (g *Graph) targetURL(a *String) string {
	if _, ok := g.TargetByName[a]; ok {
		return fmt.Sprintf("<a href=\"/target?t=%s\">%s</a>\n", a.String(), html.EscapeString(a.String()))
	} else {
		return html.EscapeString(a.String())
	}
}
Пример #18
0
// computes inline diff for the given line
func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) template.HTML {
	if setting.Git.DisableDiffHighlight {
		return template.HTML(html.EscapeString(diffLine.Content[1:]))
	}
	var (
		compareDiffLine *DiffLine
		diff1           string
		diff2           string
	)

	// try to find equivalent diff line. ignore, otherwise
	switch diffLine.Type {
	case DIFF_LINE_ADD:
		compareDiffLine = diffSection.GetLine(DIFF_LINE_DEL, diffLine.RightIdx)
		if compareDiffLine == nil {
			return template.HTML(html.EscapeString(diffLine.Content))
		}
		diff1 = compareDiffLine.Content
		diff2 = diffLine.Content
	case DIFF_LINE_DEL:
		compareDiffLine = diffSection.GetLine(DIFF_LINE_ADD, diffLine.LeftIdx)
		if compareDiffLine == nil {
			return template.HTML(html.EscapeString(diffLine.Content))
		}
		diff1 = diffLine.Content
		diff2 = compareDiffLine.Content
	default:
		return template.HTML(html.EscapeString(diffLine.Content))
	}

	diffRecord := diffMatchPatch.DiffMain(diff1[1:], diff2[1:], true)
	diffRecord = diffMatchPatch.DiffCleanupEfficiency(diffRecord)

	return diffToHTML(diffRecord, diffLine.Type)
}
Пример #19
0
func writeDiffHTML(out *bytes.Buffer, from, to, header string) {
	dmp := diffmatchpatch.New()
	diff := dmp.DiffMain(from, to, true)
	diff = dmp.DiffCleanupSemantic(diff)

	out.WriteString("<h1>" + html.EscapeString(header) + "</h1>\n<pre>")

	// write the diff
	for _, chunk := range diff {
		txt := html.EscapeString(chunk.Text)
		txt = strings.Replace(txt, "\n", "↩\n", -1)
		switch chunk.Type {
		case diffmatchpatch.DiffInsert:
			out.WriteString(`<ins style="background:#e6ffe6;">`)
			out.WriteString(txt)
			out.WriteString(`</ins>`)
		case diffmatchpatch.DiffDelete:
			out.WriteString(`<del style="background:#ffe6e6;">`)
			out.WriteString(txt)
			out.WriteString(`</del>`)
		case diffmatchpatch.DiffEqual:
			out.WriteString(`<span>`)
			out.WriteString(txt)
			out.WriteString(`</span>`)
		}
	}
	if out.Len() > MaxDetailsLen {
		out.Truncate(MaxDetailsLen)
		out.WriteString("\n\n[TRUNCATED]")
	}
	out.WriteString("</pre>")
}
Пример #20
0
func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTML {
	buf := bytes.NewBuffer(nil)

	// Reproduce signs which are cutted for inline diff before.
	switch lineType {
	case DIFF_LINE_ADD:
		buf.WriteByte('+')
	case DIFF_LINE_DEL:
		buf.WriteByte('-')
	}

	for i := range diffs {
		switch {
		case diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DIFF_LINE_ADD:
			buf.Write(addedCodePrefix)
			buf.WriteString(html.EscapeString(diffs[i].Text))
			buf.Write(codeTagSuffix)
		case diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DIFF_LINE_DEL:
			buf.Write(removedCodePrefix)
			buf.WriteString(html.EscapeString(diffs[i].Text))
			buf.Write(codeTagSuffix)
		case diffs[i].Type == diffmatchpatch.DiffEqual:
			buf.WriteString(html.EscapeString(diffs[i].Text))
		}
	}

	return template.HTML(buf.Bytes())
}
Пример #21
0
func Handle(c HTTPContextLogger, f func() error, scopes ...string) {
	defer func() {
		if e := recover(); e != nil {
			c.Errorf("PANIC\n%v\nRequest: %+v\nStack: %s", e, c.Req(), utils.Stack())
			panic(e)
		}
	}()
	err := c.CheckScopes(scopes)
	if err == nil {
		err = f()
	}
	if err != nil {
		if errResponse, ok := err.(Responder); ok {
			if err2 := errResponse.Respond(c); err2 != nil {
				c.Resp().WriteHeader(500)
				fmt.Fprintf(c.Resp(), html.EscapeString(fmt.Sprintf("Unable to render the proper error %+v: %v", err, err2)))
			}
		} else {
			c.Resp().WriteHeader(500)
			fmt.Fprintf(c.Resp(), html.EscapeString(fmt.Sprintf("%v", err)))
		}
		if c.Resp().Status() >= 500 {
			c.Errorf("%v\n%v\n\n", c.Req().URL, err)
		} else {
			c.Warningf("%v\n%v\n\n", c.Req().URL, err)
		}
		stackErr := errors.Wrap(err, 1)
		c.Infof("%s", stackErr.ErrorStack())
	}
}
func main() {
	raw := []string{
		"hello",
		"<i>Hello</i>",
		"alert('hello');",
		"foo & bar",
		`"how are you?" He asked.`,
	}

	log.Println("html.EscapeString")
	for _, s := range raw {
		log.Printf("\t%s -> %s", s, html.EscapeString(s))
	}

	log.Println("html.UnescapeString(html.EscapeString)")
	for _, s := range raw {
		flipped := html.UnescapeString(html.EscapeString(s))
		log.Printf("\t%s -> %s", s, flipped)
	}

	escaped := []string{
		"&#225",
		"&raquo;",
		"&middot;",
		"&lt;i&gt;htllo&lt;/i&gt;",
	}

	log.Println("html.UnescapeString")
	for _, s := range escaped {
		log.Printf("\t%s -> %s", s, html.UnescapeString(s))
	}
}
Пример #23
0
// Should produce original html as seen by parser.
// Two differences: a) selfclosing tags are selfclosing in the output
// and b) attribute values and text is escaped.
func (n *Node) Html() (s string) {
	s = "<" + n.Name
	for _, a := range n.Attr {
		s += " " + a.Key + "=\"" + html.EscapeString(a.Val) + "\""
	}
	if len(n.class) > 0 {
		s += " class=\""
		for i, c := range n.class {
			if i > 0 {
				s += " "
			}
			s += c
		}
		s += "\""
	}
	s += ">"
	for _, c := range n.subs {
		if c.Name == TEXT_NODE {
			s += html.EscapeString(c.Text)
		} else {
			s += c.Html()
		}
	}
	switch n.Name {
	case "img", "meta", "br", "input":
		s += " />"
	default:
		s += "</" + n.Name + ">"
	}
	return
}
Пример #24
0
// Formats the block content as html, without enclosing tags
func (b *BaseBlock) FormatHtmlText() string {
	t := html.EscapeString(b.Text)
	// store one more to be able to compute offsets[len(text)]
	offsets := make([]int, len(b.Text)+1)
	// compute byte offsets for utf8 string
	off := 0
	index := 0
	for k, r := range b.Text {
		offsets[index] = k + off
		off += len([]rune(html.EscapeString(string([]rune{r})))) - 1
		index++
	}
	offsets[index] = len(b.Text) + off
	for _, s := range b.Spans {
		begin := s.HtmlBeginTag()
		end := s.HtmlEndTag()
		t = t[:offsets[s.GetStart()]] + begin + t[offsets[s.GetStart()]:offsets[s.GetEnd()]] + end + t[offsets[s.GetEnd()]:]
		for i := s.GetStart(); i < s.GetEnd(); i++ {
			offsets[i] += len(begin)
		}
		for i := s.GetEnd(); i < len(offsets); i++ {
			offsets[i] += len(begin) + len(end)
		}
	}
	return t
}
Пример #25
0
// HTTP handler for _dumpchannel
func (h *handler) handleDumpChannel() error {
	channelName := h.PathVar("channel")
	since := h.getIntQuery("since", 0)
	base.LogTo("HTTP", "Dump channel %q", channelName)

	chanLog := h.db.GetChangeLog(channelName, since)
	if chanLog == nil {
		return base.HTTPErrorf(http.StatusNotFound, "no such channel")
	}
	title := fmt.Sprintf("/%s: “%s” Channel", html.EscapeString(h.db.Name), html.EscapeString(channelName))
	h.setHeader("Content-Type", `text/html; charset="UTF-8"`)
	h.response.Write([]byte(fmt.Sprintf(
		`<!DOCTYPE html><html><head><title>%s</title></head><body>
		<h1>%s</h1><code>
		<p>Since = %d</p>
		<table border=1>
		`,
		title, title, chanLog[0].Sequence-1)))
	h.response.Write([]byte("\t<tr><th>Seq</th><th>Doc</th><th>Rev</th><th>Flags</th></tr>\n"))
	for _, entry := range chanLog {
		h.response.Write([]byte(fmt.Sprintf("\t<tr><td>%d</td><td>%s</td><td>%s</td><td>%08b</td>",
			entry.Sequence,
			html.EscapeString(entry.DocID), html.EscapeString(entry.RevID), entry.Flags)))
		h.response.Write([]byte("</tr>\n"))
	}
	h.response.Write([]byte("</table>\n</code></html></body>"))
	return nil
}
Пример #26
0
//  AuthAuthenticate performs an API request for op=auth_authenticate
//
//  This method requires one argument of type innGateApi.AuthAuthenticateRequest.
//  See the ANTLabs API for more information regarding elements of the argument.
//  The example below demonstrates how to send a request.
//
//Example:
//  ant := innGateApi.Host{
// 	   Host : "ant.example.com", //can be an IP or hostname
//  }
//  resp, err := ant.AuthAuthenticate(innGateApi.AuthAuthenticateRequest{Code: "abc123"})
//  if(err != nil){ panic(err) }
//  fmt.Println("\n\nResult of authentication request:", resp.Result)
func (api *Host) AuthAuthenticate(request AuthAuthenticateRequest) (result *authAuthenticateResponse, err error) {
	ant := api.ant()
	request.op = "auth_authenticate"

	result = &authAuthenticateResponse{}

	query := "api_password="******"&op=" + request.op
	if request.Code != "" {
		query += "&code=" + request.Code
	}
	if request.UserId != "" {
		query += "&userid=" + html.EscapeString(request.UserId)
	}
	if request.Password != "" {
		query += "&password="******"radiusattrs":
			result.RadiusAttrs = strings.Split(v[2], "|")
		}
	}

	return result, nil
}
Пример #27
0
/*
添加管理员
*/
func (this *Model) AddUser(name, psw string) error {
	username := html.EscapeString(name)
	password := html.EscapeString(psw)
	db, err := sql.Open("mysql", "root:dumx@tcp(localhost:3306)/myblog?charset=utf8")
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer db.Close()
	querySql := "select 1 from myblog.users WHERE name = ' " + username + "'"
	rows, err := db.Query(querySql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	if rows.Next() {
		return errors.New("user " + username + "exsited")
	}

	insertSql := "INSERT myblog.users SET name=?, password=?"
	stmt, err := db.Prepare(insertSql)
	if nil != err {
		logger.Errorln(err)
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(username, password)
	if nil != err {
		logger.Errorln(err)
		return err
	}

	return nil
}
Пример #28
0
//  AuthLogout performs the an API request for op=auth_logout
//
//  This method requires one argument of type innGateApi.AuthLoginRequest.
//  See the ANTLabs API for more information regarding elements of the argument.
//  The example below demonstrates how to send a request.
//
//Example:
//  ant := innGateApi.Host{
// 	   Host : "ant.example.com", //can be an IP or hostname
//  }
//  resp, err := ant.AuthLogout(innGateApi.AuthLogoutRequest{Sid : "86cb1a5deb036467a9c2bc36e13971ef"})
//  if(err != nil){ panic(err) }
//  fmt.Println("\n\nLogout result:", resp.Result)
func (api *Host) AuthLogout(request AuthLogoutRequest) (result *authLogoutResponse, err error) {
	ant := api.ant()
	request.op = "auth_logout"
	result = &authLogoutResponse{}

	query := "api_password="******"&op=" + request.op
	if request.Sid != "" {
		query += "&sid=" + html.EscapeString(request.Sid)
	}
	if request.ClientMac != "" {
		query += "&client_mac=" + html.EscapeString(request.ClientMac)
	}

	parsed_body, err := ant.InnGateApiRequest(query)
	if err != nil {
		return nil, err
	}

	err = result.findCommoners(parsed_body)
	//if( err != nil){ return nil, err }

	for _, v := range parsed_body {
		switch v[1] {
		case "accounting":
			result.Accounting = v[2]
		case "sid":
			result.Sid = v[2]
		case "client_mac":
			result.ClientMac = v[2]
		}
	}

	return result, nil
}
Пример #29
0
func xml_balance(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	w.Header()["Content-Type"] = []string{"text/xml"}
	w.Write([]byte("<unspent>"))

	wallet.LockBal()
	for i := range wallet.MyBalance {
		w.Write([]byte("<output>"))
		fmt.Fprint(w, "<txid>", btc.NewUint256(wallet.MyBalance[i].TxPrevOut.Hash[:]).String(), "</txid>")
		fmt.Fprint(w, "<vout>", wallet.MyBalance[i].TxPrevOut.Vout, "</vout>")
		fmt.Fprint(w, "<value>", wallet.MyBalance[i].Value, "</value>")
		fmt.Fprint(w, "<inblock>", wallet.MyBalance[i].MinedAt, "</inblock>")
		fmt.Fprint(w, "<blocktime>", get_block_time(wallet.MyBalance[i].MinedAt), "</blocktime>")
		fmt.Fprint(w, "<addr>", wallet.MyBalance[i].BtcAddr.String(), "</addr>")
		fmt.Fprint(w, "<wallet>", html.EscapeString(wallet.MyBalance[i].BtcAddr.Extra.Wallet), "</wallet>")
		fmt.Fprint(w, "<label>", html.EscapeString(wallet.MyBalance[i].BtcAddr.Extra.Label), "</label>")
		fmt.Fprint(w, "<virgin>", fmt.Sprint(wallet.MyBalance[i].BtcAddr.Extra.Virgin), "</virgin>")
		w.Write([]byte("</output>"))
	}
	wallet.UnlockBal()
	w.Write([]byte("</unspent>"))
}
Пример #30
0
func apiSearch(store StuffStore, out http.ResponseWriter, r *http.Request) {
	defer ElapsedPrint("Query", time.Now())
	// Allow very brief caching, so that editing the query does not
	// necessarily has to trigger a new server roundtrip.
	out.Header().Set("Cache-Control", "max-age=10")
	query := r.FormValue("q")
	if query == "" {
		out.Write([]byte("{\"count\":0, \"info\":\"\", \"items\":[]}"))
		return
	}
	start := time.Now()
	searchResults := store.Search(query)
	elapsed := time.Now().Sub(start)
	elapsed = time.Microsecond * ((elapsed + time.Microsecond/2) / time.Microsecond)
	outlen := 24 // Limit max output
	if len(searchResults) < outlen {
		outlen = len(searchResults)
	}
	jsonResult := &JsonSearchResult{
		Count: len(searchResults),
		Info:  fmt.Sprintf("%d results (%s)", len(searchResults), elapsed),
		Items: make([]JsonSearchResultRecord, outlen),
	}

	for i := 0; i < outlen; i++ {
		var c = searchResults[i]
		jsonResult.Items[i].Id = c.Id
		jsonResult.Items[i].Label = "<b>" + html.EscapeString(c.Value) + "</b> " +
			html.EscapeString(c.Description) +
			fmt.Sprintf(" <span class='idtxt'>(ID:%d)</span>", c.Id)
	}
	json, _ := json.Marshal(jsonResult)
	out.Write(json)
}