本文整理汇总了Golang中html/template.JSEscapeString函数的典型用法代码示例。如果您正苦于以下问题:Golang JSEscapeString函数的具体用法?Golang JSEscapeString怎么用?Golang JSEscapeString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了JSEscapeString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: JSEscape
// 安全过滤
func JSEscape(topics []*model.Topic) []*model.Topic {
for i, topic := range topics {
topics[i].Title = template.JSEscapeString(topic.Title)
topics[i].Content = template.JSEscapeString(topic.Content)
}
return topics
}
示例2: handleJsError
func handleJsError(jsCode string, err error) string {
if err != nil {
fmt.Fprintln(os.Stderr, err)
return `console.error("` + template.JSEscapeString(err.Error()) + `");`
}
return jsCode
}
示例3: render
func (t *Template) render(rctx core.RenderContext) string {
b := &bytes.Buffer{}
// Update functions for current rendering context.
t.tmpl.Funcs(map[string]interface{}{
"slot": func(name, elt string) template.HTML {
s := t.node.Slot(name)
if elt == "" {
return template.HTML(s.Node().Render(rctx))
}
return template.HTML(fmt.Sprintf("<%s id='%s'>%s</%s>", elt, s.ID(), s.Node().Render(rctx), elt))
},
"event": func(name string) template.JS {
return template.JS(fmt.Sprintf("stdweb.events.onClick('%s', '%s', event)", template.JSEscapeString(t.node.ID()), template.JSEscapeString(name)))
},
})
err := t.tmpl.Execute(b, &tplData{
ID: t.node.ID(),
RunID: rctx.RunID(),
UpdateID: rctx.UpdateID(),
Data: t.data,
})
if err == nil {
return b.String()
}
return html.EscapeString(err.Error())
}
示例4: serveLive
// serveLive serves reloader and serves the web socket connection
func (server *Server) serveLive(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate, no-cache")
switch path.Base(r.URL.Path) {
case "~pkg.js":
w.Header().Set("Content-Type", "application/javascript")
w.Write([]byte(jspackage))
origurl, err := url.ParseRequestURI(r.RequestURI)
origpath := r.RequestURI
if err != nil && origurl != nil {
origpath = origurl.Path
}
rootpath := template.JSEscapeString(path.Dir(origpath))
w.Write([]byte(strings.Replace(jsreloader, rootPathMarker, rootpath, -1)))
case "~pkg.json":
server.info(w, r)
case "~pkg.css":
// this will be handled by reloader
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte{'\n'})
case "~live":
server.socket.ServeHTTP(w, r)
default:
server.bundle.ServeFile(w, r)
}
}
示例5: Example_escape
func Example_escape() {
const s = `"Fran & Freddie's Diner" <[email protected]>`
v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<[email protected]>`}
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...))
// Output:
// "Fran & Freddie's Diner" <[email protected]>
// "Fran & Freddie's Diner" <[email protected]>
// "Fran & Freddie's Diner"32<[email protected]>
// \"Fran & Freddie\'s Diner\" \[email protected]\x3E
// \"Fran & Freddie\'s Diner\" \[email protected]\x3E
// \"Fran & Freddie\'s Diner\"32\[email protected]\x3E
// %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E
}
示例6: handleRoot
func handleRoot(w http.ResponseWriter, r *http.Request, db *sql.DB) {
if r.Method == "GET" {
http.ServeFile(w, r, "./resources/index.html")
} else if r.Method == "POST" {
url := r.FormValue("url")
escaped := template.JSEscapeString(url)
if escaped != url {
fmt.Fprintln(w, "Sorry, no XSS attacks")
return
} else if len(escaped) < 2 {
fmt.Fprintln(w, "Error: invalid url")
return
}
escaped = strings.TrimPrefix(escaped, "http://")
escaped = strings.TrimPrefix(escaped, "https://")
escaped = strings.TrimPrefix(escaped, "www.")
var short string
query := "SELECT short FROM url_mappings WHERE url=?;"
err := db.QueryRow(query, escaped).Scan(&short)
if err != nil {
short = newUrlMapping(escaped, db)
}
fmt.Fprintf(w, "<a href=\"localhost%s/%s\">localhost%s/%s</a>", port, short, port, short)
} else {
fmt.Fprintf(w, "405: method not allowed")
}
}
示例7: RawOutput
func RawOutput(r *app.Request) error {
if err := hooks.PreCompile(); err != nil {
return err
}
if err := gss.Compile(); err != nil {
return err
}
if err := soy.Compile(); err != nil {
return err
}
_, namespaces, err := js.GenerateDeps("input-production")
if err != nil {
return err
}
log.Println("Output RAW mode")
conf := config.Current()
content := bytes.NewBuffer(nil)
base := path.Join(conf.Library.Root, "closure", "goog", "base.js")
if err := addFile(content, base); err != nil {
return err
}
if err := addFile(content, path.Join(conf.Build, config.RENAMING_MAP_NAME)); err != nil {
return err
}
if err := addFile(content, path.Join(conf.Build, config.DEPS_NAME)); err != nil {
return err
}
if err := hooks.PostCompile(); err != nil {
return err
}
css := make([]byte, 0)
if conf.Gss != nil {
css, err = ioutil.ReadFile(filepath.Join(conf.Build, config.CSS_NAME))
if err != nil {
return app.Error(err)
}
}
data := map[string]interface{}{
"Content": template.HTML(string(content.Bytes())),
"Port": config.Port,
"LT": template.HTML("<"),
"Namespaces": template.HTML("'" + strings.Join(namespaces, "', '") + "'"),
"Css": template.HTML(template.JSEscapeString(string(css))),
}
r.W.Header().Set("Content-Type", "text/javascript")
return r.ExecuteTemplate([]string{"raw"}, data)
}
示例8: js
// js formats value, which should be one of bool, int64, float64, time.Time or string as javascript value.
func js(v interface{}) template.JS {
var r string
if v == nil {
r = "null"
} else if t, ok := v.(time.Time); ok {
if day := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()); t.Equal(day) {
r = "'" + t.Format(YMD) + "'"
} else {
r = "'" + t.Format(YMDHMS) + "'"
}
} else {
switch v := v.(type) {
case string:
r = "'" + template.JSEscapeString(v) + "'"
default:
r = template.JSEscapeString(fmt.Sprintf("%v", v))
}
}
return template.JS(r)
}
示例9: TestHTMLEscape
func TestHTMLEscape(t *testing.T) {
const s = `"Fran & Freddie's Diner" <[email protected]>`
v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<[email protected]>`}
fmt.Println(template.HTMLEscapeString(s))
template.HTMLEscape(os.Stdout, []byte(s))
fmt.Fprint(os.Stdout, "")
fmt.Println(template.JSEscapeString(s))
fmt.Println(template.JSEscaper(v...))
fmt.Println(template.URLQueryEscaper(v...))
}
示例10: WebThingTable
func WebThingTable(w http.ResponseWriter, r *http.Request) {
thing := context.Get(r, ContextKeyThing).(*Thing)
account := context.Get(r, ContextKeyAccount).(*Account)
if !thing.EditableById(account.Character) {
http.Error(w, "No access to table data", http.StatusForbidden)
return
}
if r.Method == "POST" {
updateText := r.PostFormValue("updated_data")
var updates map[string]interface{}
err := json.Unmarshal([]byte(updateText), &updates)
if err != nil {
// aw carp
// TODO: set a flash?
http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther)
return
}
deleteText := r.PostFormValue("deleted_data")
var deletes map[string]interface{}
err = json.Unmarshal([]byte(deleteText), &deletes)
if err != nil {
// aw carp
// TODO: set a flash?
http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther)
return
}
thing.Table = mergeMapInto(updates, thing.Table)
thing.Table = deleteMapFrom(deletes, thing.Table)
World.SaveThing(thing)
http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther)
return
}
RenderTemplate(w, r, "thing/page/table.html", map[string]interface{}{
"Title": fmt.Sprintf("Edit all data – %s", thing.Name),
"Thing": thing,
"json": func(v interface{}) interface{} {
output, err := json.MarshalIndent(v, "", " ")
if err != nil {
escapedError := template.JSEscapeString(err.Error())
message := fmt.Sprintf("/* error encoding JSON: %s */ {}", escapedError)
return template.JS(message)
}
return template.JS(output)
},
})
}
示例11: get
func (p *Polling) get(w http.ResponseWriter, r *http.Request) {
if !p.getLocker.TryLock() {
http.Error(w, "overlay get", http.StatusBadRequest)
return
}
if p.getState() != stateNormal {
http.Error(w, "closed", http.StatusBadRequest)
return
}
defer func() {
if p.getState() == stateClosing {
if p.postLocker.TryLock() {
p.setState(stateClosed)
p.callback.OnClose(p)
p.postLocker.Unlock()
}
}
p.getLocker.Unlock()
}()
<-p.sendChan
if j := r.URL.Query().Get("j"); j != "" {
// JSONP Polling
w.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
tmp := bytes.Buffer{}
p.encoder.EncodeTo(&tmp)
pl := template.JSEscapeString(tmp.String())
w.Write([]byte("___eio[" + j + "](\""))
w.Write([]byte(pl))
w.Write([]byte("\");"))
} else {
// XHR Polling
if p.encoder.IsString() {
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
p.encoder.EncodeTo(w)
}
}
示例12: serveMainJS
func serveMainJS(w http.ResponseWriter, r *http.Request) {
name, err := appName(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
out, err := createJSIfNeeded(name)
if err != nil {
t := template.JSEscapeString(template.HTMLEscapeString(err.Error()))
js := `
window.onload = function() {
document.body.innerHTML="<pre style='white-space: pre-wrap;'><code>` + t + `</code></pre>";
}`
w.Header().Set("Content-Type", "text/javascript")
fmt.Fprintf(w, js)
return
}
if err := serveFile(w, out, "text/javascript"); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
示例13: JSONP
// JSONP writes jsonp to response body.
func (output *BeegoOutput) JSONP(data interface{}, hasIndent bool) error {
output.Header("Content-Type", "application/javascript; charset=utf-8")
var content []byte
var err error
if hasIndent {
content, err = json.MarshalIndent(data, "", " ")
} else {
content, err = json.Marshal(data)
}
if err != nil {
http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
return err
}
callback := output.Context.Input.Query("callback")
if callback == "" {
return errors.New(`"callback" parameter required`)
}
callbackContent := bytes.NewBufferString(" " + template.JSEscapeString(callback))
callbackContent.WriteString("(")
callbackContent.Write(content)
callbackContent.WriteString(");\r\n")
return output.Body(callbackContent.Bytes())
}
示例14: Jsonp
//serve jsonp
func (this *ContextOutput) Jsonp(content interface{}, hasIntent bool) error {
this.Header("Content-Type", "application/javascript; charset=utf-8")
var jsonBody []byte
var err error
if hasIntent {
jsonBody, err = json.MarshalIndent(content, "", " ")
} else {
jsonBody, err = json.Marshal(content)
}
if err != nil {
http.Error(this.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
return err
}
callback := this.Context.Input.GetParam("callback")
if callback == "" {
return errors.New("Callback not set.")
}
cbBody := bytes.NewBufferString(" " + template.JSEscapeString(callback))
cbBody.WriteString("(")
cbBody.Write(jsonBody)
cbBody.WriteString(");\r\n")
this.Body(cbBody.Bytes())
return nil
}
示例15: Clean
func Clean(val string) string {
return html.EscapeString(template.JSEscapeString(template.HTMLEscapeString(val)))
}