コード例 #1
0
ファイル: topic.go プロジェクト: BillyMC/studygolang
// 安全过滤
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
0
ファイル: gopherjs_http.go プロジェクト: wutaizeng/kapacitor
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
0
ファイル: template.go プロジェクト: Palats/stdweb
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
0
ファイル: server.go プロジェクト: raintreeinc/livepkg
// 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
0
ファイル: example_test.go プロジェクト: wheelcomplex/go-1
func Example_escape() {
	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...))

	// Output:
	// &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;[email protected]&gt;
	// &#34;Fran &amp; Freddie&#39;s Diner&#34; &lt;[email protected]&gt;
	// &#34;Fran &amp; Freddie&#39;s Diner&#34;32&lt;[email protected]&gt;
	// \"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
0
ファイル: gus.go プロジェクト: marksilvis/gus
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
0
ファイル: raw.go プロジェクト: ernestoalejo/closurer
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
0
ファイル: js.go プロジェクト: grafikdb/grafik-public
// 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
0
ファイル: template_HTML_test.go プロジェクト: gavinzhs/testgo
func TestHTMLEscape(t *testing.T) {
	const s = `"Fran & Freddie's Diner" <*****@*****.**>`
	v := []interface{}{`"Fran & Freddie's Diner"`, ' ', `<*****@*****.**>`}

	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
0
ファイル: web.go プロジェクト: natmeox/mess
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
0
ファイル: server.go プロジェクト: zhouhui8915/engine.io-go
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
0
ファイル: main.go プロジェクト: hajimehoshi/ebiten
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
0
ファイル: output.go プロジェクト: GuyCheung/beego
// 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
0
ファイル: output.go プロジェクト: jesusslim/slimgo
//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
0
ファイル: helpers.go プロジェクト: jzaikovs/core
func Clean(val string) string {
	return html.EscapeString(template.JSEscapeString(template.HTMLEscapeString(val)))
}
コード例 #16
0
ファイル: filtercollection.go プロジェクト: d2g/cloudpathway
/**
 * Returns a HTML safe escaped version of the name of this collection.
 */
func (this *FilterCollection) EscapedName() string {
	result := strings.Replace(this.Name, " ", "+", -1)
	return template.JSEscapeString(result)
}
コード例 #17
0
ファイル: webcmd.go プロジェクト: cfstras/cfmedias
func (n *NetCmdLine) Start(coreInstance core.Core, db *db.DB) {
	n.core = coreInstance
	n.db = db

	m := martini.Classic()
	n.martini = m
	m.Use(render.Renderer())

	m.Group("/api", func(r martini.Router) {
		r.Get("/:cmd", n.api)
		r.Post("/:cmd", n.api)
	}, mapArgs, n.authenticate)

	m.Group("/debug/pprof", func(r martini.Router) {
		r.Any("/", pprof.Index)
		r.Any("/cmdline", pprof.Cmdline)
		r.Any("/profile", pprof.Profile)
		r.Any("/symbol", pprof.Symbol)
		r.Any("/block", pprof.Handler("block").ServeHTTP)
		r.Any("/heap", pprof.Handler("heap").ServeHTTP)
		r.Any("/goroutine", pprof.Handler("goroutine").ServeHTTP)
		r.Any("/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
	})

	mapAsset := func(c martini.Context, r *http.Request) {
		c.Map(r.URL.Path[1:])
	}
	m.Get("/", func() (string, error) {
		b, err := Asset("index.html")
		if err != nil {
			return "", err
		}
		str := string(b)
		var files []string
		for _, k := range AssetNames() {
			if strings.HasPrefix(k, "js/") && strings.HasSuffix(k, ".js") {
				files = append(files, k)
			}
		}
		//TODO sort files?
		replaceStart, replaceEnd := `<script src="/`, `"></script>`
		var replace string
		for _, v := range files {
			replace += replaceStart + v + replaceEnd
		}
		str = strings.Replace(str, `<script src="/vendor/js/app.js"></script>`, replace, 1)
		return str, err
	})
	//TODO if development
	m.Get("/vendor/js/templates.js", mapAsset, setMime, func() (string, error) {
		templateFolder := "templates/"
		extension := ".hbs"
		var files []string
		for _, k := range AssetNames() {
			if strings.HasPrefix(k, templateFolder) && strings.HasSuffix(k, extension) {
				k = k[len(templateFolder):]
				k = k[:len(k)-len(extension)]
				files = append(files, k)
			}
		}
		start, mid, end := `Ember.TEMPLATES['`,
			`'] = Ember.Handlebars.compile("`, `");`+"\n"
		var result string
		for _, v := range files {
			templ, err := Asset(templateFolder + v + extension)
			if err != nil {
				return "", err
			}
			result += start + v + mid + template.JSEscapeString(string(templ)) + end
		}
		return result, nil
	})

	m.Get("/vendor/**", mapAsset, setMime, Asset)
	m.Get("/css/**", mapAsset, setMime, Asset)
	m.Get("/js/**", mapAsset, setMime, Asset)
	m.Get("/templates/**", mapAsset, setMime, Asset)

	os.Setenv("PORT", fmt.Sprint(config.Current.WebPort))
	m.Run()
}
コード例 #18
0
ファイル: base.fns.go プロジェクト: yh453926638/scaffold
	}

	DatetimeFormat = func() string {
		return revel.Config.StringDefault("format.datetime", "2006/01/02 15:04:05")
	}

	JsonEncode = func(value interface{}) string {
		if b, err := json.Marshal(value); err == nil {
			return string(b)
		}

		return ""
	}

	SecureEscape = func(src interface{}) string {
		return template.HTMLEscapeString(template.JSEscapeString(fmt.Sprintf("%v", src)))
	}

	JavascriptEscape = func(src interface{}) string {
		return template.JSEscapeString(fmt.Sprintf("%v", src))
	}

	Pagination = func(widget, name string, total, page_size, page_no int64) template.HTML {
		pages := []Page{}
		if page_size == 0 || total == 0 {
			return template.HTML("")
		}

		num := total / page_size
		if total%page_size > 0 {
			num = num + 1
コード例 #19
0
ファイル: handlers.go プロジェクト: bigwhoop/browsapi
// configHandler outputs  a JS config file that configures the browsapi JS app.
func configHandler(rsp http.ResponseWriter, rqst *http.Request) {
	reloadConfig()

	rsp.Header().Set("Content-Type", "text/javascript; charset=utf-8")
	rsp.WriteHeader(200)

	fmt.Fprintf(rsp, "browsapi.Config.setVersion('%s');\n\n", Version)
	fmt.Fprintf(rsp, "browsapi.Config.setRequestLogType('%s');\n\n", template.JSEscapeString(config.RequestLog))

	if len(configPath) > 0 {
		fmt.Fprintf(rsp, "browsapi.Config.setLoadedConfigFileName('%s');\n\n", template.JSEscapeString(filepath.Base(configPath)))
	}

	for name, description := range config.Params {
		fmt.Fprintf(
			rsp,
			"browsapi.Config.setUserOption(new browsapi.UserOption('%s', '%s'));\n",
			template.JSEscapeString(name),
			template.JSEscapeString(description),
		)
	}

	fmt.Fprintf(rsp, "\n")

	for _, host := range config.Servers {
		if host.Ignore {
			continue
		}

		headers, err := json.Marshal(host.GetHeaders())
		if err != nil {
			continue
		}

		fmt.Fprintf(
			rsp,
			"browsapi.Config.setHost('%s', new browsapi.Host('%s', '%s', %s, '%s', '%s'));\n",
			template.JSEscapeString(host.Name),
			template.JSEscapeString(host.GetURL()),
			template.JSEscapeString(host.GetAuth()),
			headers,
			template.JSEscapeString(host.GetUsername()),
			template.JSEscapeString(host.GetPassword()),
		)
	}

	fmt.Fprintf(rsp, "\n")

	for alias, path := range config.Requests {
		fmt.Fprintf(
			rsp,
			"browsapi.Config.setPath('%s', '%s');\n",
			template.JSEscapeString(alias),
			template.JSEscapeString(path),
		)
	}
}