Esempio n. 1
0
// Renderer is a Middleware that maps a render.Render service into the Martini handler chain. An single variadic render.Options
// struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default
// file extension is ".tmpl".
//
// If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the
// MARTINI_ENV environment variable to "production"
func Renderer(options ...Options) martini.Handler {
	opt := prepareOptions(options)
	cs := prepareCharset(opt.Charset)
	t := compile(opt)
	compiledAmberFiles, err := compileAmberFiles(opt)
	if err != nil {
		panic(err)
	}

	// Check no name conflicts between template and amber
	for n := range compiledAmberFiles {
		found := t.Lookup(n)
		if found != nil {
			panic(fmt.Errorf("Template name conflict: \"%s\"", n))
		}
	}

	bufpool = bpool.NewBufferPool(64)
	return func(res http.ResponseWriter, req *http.Request, c martini.Context) {
		var tc *template.Template
		var at map[string]*template.Template
		if martini.Env == martini.Dev {
			// recompile for easy development
			tc = compile(opt)
			at, _ = compileAmberFiles(opt)
		} else {
			// use a clone of the initial template
			tc, _ = t.Clone()
			at = compiledAmberFiles
		}
		c.MapTo(&renderer{res, req, tc, opt, cs, at}, (*Render)(nil))
	}
}
Esempio n. 2
0
func init() {
	// Create buffer pool
	bufpool = bpool.NewBufferPool(64)

	// Get the contents of all layouts.
	layoutData := make(map[string]string)
	for _, lname := range layouts.AssetNames() {
		d, _ := layouts.Asset(lname)
		layoutData[lname] = string(d)
	}

	// For each template, we parse it.
	templatesMap = make(map[string]*template.Template)
	for _, aname := range templates.AssetNames() {
		tname := filepath.Base(aname)

		// Create new template with functions
		tmpl := template.New(tname).Funcs(templateFuncs)

		// Get the template's data
		d, _ := templates.Asset(aname)

		// Parse the main template, then all the layouts.
		tmpl = template.Must(tmpl.Parse(string(d)))
		for _, layout := range layouts.AssetNames() {
			tmpl = template.Must(tmpl.Parse(layoutData[layout]))
		}

		// Insert
		templatesMap[tname] = tmpl
	}
}
Esempio n. 3
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	bufpool = bpool.NewBufferPool(64)

	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	templateFiles, err := filepath.Glob("templates/*.tmpl")
	if err != nil {
		log.Fatal(err)
	}

	for _, t := range templateFiles {
		fmt.Println(filepath.Base(t))
		templates[filepath.Base(t)] = template.Must(template.ParseFiles("templates/base.ghtml", t))
	}

	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/cats", catsHandler)
	http.HandleFunc("/favicon.ico", faviconHandler)
	http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	log.Fatal(http.ListenAndServe(":9000", nil))
}
Esempio n. 4
0
func loadTemplates() {
	if loaded {
		return
	}

	templates = make(map[string]*template.Template)

	bufpool = bpool.NewBufferPool(64)

	layoutTemplates := map[string][]string{
		"web/layouts/outside.html": []string{
			"./web/includes/register.html",
			"./web/includes/login.html",
		},
		"web/layouts/inside.html": []string{
			"./web/includes/authorize.html",
		},
	}

	for layout, includes := range layoutTemplates {
		for _, include := range includes {
			files := []string{include, layout}
			templates[filepath.Base(include)] = template.Must(template.ParseFiles(files...))
		}
	}

	loaded = true
}
Esempio n. 5
0
// Load templates on program initialisation
func init() {
	bufpool = bpool.NewBufferPool(64)

	if templates == nil {
		templates = make(map[string]*template.Template)
	}

	templatesDir := config.Config.TemplatePath

	layouts, err := filepath.Glob(templatesDir + "layouts/*.tmpl")
	if err != nil {
		log.Fatal(err)
	}

	includes, err := filepath.Glob(templatesDir + "includes/*.tmpl")
	if err != nil {
		log.Fatal(err)
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, layout := range layouts {
		files := append(includes, layout)
		templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
	}

}
Esempio n. 6
0
func init() {
	bufpool = bpool.NewBufferPool(64)
	templatesDir = Dir_Templates

	initTemplate()

	go reloadTemplate()
}
Esempio n. 7
0
func New(dir string) *Templates {

	t := make_templates(dir)

	return &Templates{
		bpool.NewBufferPool(512),
		t,
	}
}
Esempio n. 8
0
func newAlbumJob(album *zing.Album, out io.Writer) (*albumJob, error) {
	return &albumJob{
		album:         album,
		downloadQueue: make(chan zing.AlbumItem),
		downloadSync:  &sync.WaitGroup{},
		zipQueue:      make(chan zipFile, 2),
		zipSync:       &sync.WaitGroup{},
		zipWriter:     out,
		bufferPool:    bpool.NewBufferPool(12),
	}, nil
}
Esempio n. 9
0
func newQueue(name string, store *Store, cfHandle *rocks.ColumnFamilyHandle, useTailing bool) *Queue {
	q := &Queue{
		name:       name,
		useTailing: useTailing,
		store:      store,
		cfHandle:   cfHandle,
		bufPool:    bpool.NewBufferPool(64),
	}
	q.initQueue()
	return q
}
Esempio n. 10
0
func Renderer(options ...Options) macaron.Handler {
	opt := prepareOptions(options)
	cs := prepareCharset(opt.Charset)
	bufpool = bpool.NewBufferPool(64)
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		if macaron.Env == macaron.DEV {
			// recompile for easy development
			compile(opt)
		}
		c.MapTo(&renderer{res, req, templates, opt, cs}, (*Render)(nil))
	}
}
Esempio n. 11
0
// New a renderer with given template sets and options.
func New(opt Options, tSets []*TemplateSet) *Render {
	r := &Render{
		opt:       opt,
		templates: make(map[string]*TemplateSet),
	}
	if opt.UseBufPool {
		r.bufPool = bpool.NewBufferPool(64)
	}
	for _, ts := range tSets {
		r.templates[ts.name] = ts
	}
	r.compile()
	return r
}
Esempio n. 12
0
// Renderer is a Middleware that maps a render.Render service into the Martini handler chain. An single variadic render.Options
// struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default
// file extension is ".tmpl".
//
// If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the
// MARTINI_ENV environment variable to "production"
func Renderer(options ...Options) martini.Handler {
	opt := prepareOptions(options)
	cs := prepareCharset(opt.Charset)
	t := compile(opt)
	bufpool = bpool.NewBufferPool(64)
	return func(res http.ResponseWriter, req *http.Request, c martini.Context) {
		var tc *template.Template
		if martini.Env == martini.Dev {
			// recompile for easy development
			tc = compile(opt)
		} else {
			// use a clone of the initial template
			tc, _ = t.Clone()
		}
		c.MapTo(&renderer{res, req, tc, opt, cs}, (*Render)(nil))
	}
}
Esempio n. 13
0
// send a million documents
func bufmillion(w http.ResponseWriter, r *http.Request) {

	bufpool := bpool.NewBufferPool(1024)

	for i := 0; i < 10000000; i++ {
		docId := i % docs.number
		item := docs.docMap[docs.docList[docId]]

		pw := bufpool.Get()
		err := json.NewEncoder(pw).Encode(&item)
		if err != nil {
			log.Fatalf("Error %v", err)
		}

		fmt.Fprintf(w, string(pw.Bytes())) // send data to client side
		bufpool.Put(pw)
		fmt.Fprintf(w, "\n\n")
	}
}
Esempio n. 14
0
// Get started with AppEngine
func init() {

	// Buffers are used to hold page content while we build, and then release all at once
	bufpool = bpool.NewBufferPool(32)

	// Load the various .html templates into memory
	initTemplates()

	r := new(mux.Router)

	r.Handle("/login/", NewAppHandler(LoginHandler))
	r.Handle("/share/{id}/{urltitle}", NewAppHandler(ItemHandler))
	r.Handle("/user/{username}", NewAppHandler(UserHandler))
	r.Handle("/dummy", NewAppHandler(DummyHandler))
	r.Handle("/comments/new", NewAppHandler(AddComment)).Methods("POST")
	r.Handle("/vote", NewAppHandler(VoteHandler)).Methods("POST")
	r.Handle("/", NewAppHandler(RootHandler))

	http.Handle("/", r)
}
Esempio n. 15
0
func main() {
	// Init bufferpool, used for rendering templates
	bufpool = bpool.NewBufferPool(48)

	// Load config file
	if _, err := toml.DecodeFile("config.ini", &conf); err != nil {
		log.Fatal("Couldn't parse config file: ", err)
	}

	// Setup remote repository
	repo = newRepo(
		conf.QuadStore.Endpoint,
		time.Duration(conf.QuadStore.OpenTimeout)*time.Millisecond,
		time.Duration(conf.QuadStore.ReadTimeout)*time.Millisecond,
	)

	// Parse Query bank
	qBank = sparql.LoadBank(bytes.NewBufferString(queries))

	// Register metrics
	status = registerMetrics()

	// HTTP routing
	mux := http.NewServeMux()
	var handler mainHandler
	mux.HandleFunc("/robots.txt", serveFile("data/robots.txt"))
	mux.HandleFunc("/css/styles.css", serveFile("data/css/styles.css"))
	mux.HandleFunc("/favicon.ico", serveFile("data/favicon.ico"))
	mux.HandleFunc("/.status", statusHandler)
	mux.HandleFunc("/literals", literalsHandler)
	mux.Handle("/", Timed(CountedByStatusXX(handler, "status", metrics.DefaultRegistry),
		"responseTime",
		metrics.DefaultRegistry))

	fmt.Printf("Listening on port %d ...\n", conf.ServePort)
	err := http.ListenAndServe(fmt.Sprintf(":%d", conf.ServePort), handlers.CompressHandler(mux))
	if err != nil {
		log.Println(err)
	}
}
Esempio n. 16
0
func NewTemplateManager(rootDir string) *TemplateManager {
	tm := &TemplateManager{}

	tm.bufpool = bpool.NewBufferPool(64)
	tm.rootDir = rootDir
	tm.functions = template.FuncMap{
		"time": func(value string) template.HTML {
			t, err := time.ParseInLocation("2006-01-02 15:04:05", value, time.Local)
			if err != nil {
				return template.HTML("(invalid date given)")
			}

			// get timezone information
			iso := t.Format("2006-01-02T15:04:05-0700")
			pretty := t.Format("Mon, Jan 2 2006 15:04")

			return template.HTML("<time class=\"rel\" datetime=\"" + iso + "\">" + pretty + "</time>")
		},

		"shorten": func(value string, maxlen int) string {
			length := len(value)

			if length <= maxlen {
				return value
			}

			halfs := maxlen / 2
			runes := []rune(value)

			return fmt.Sprintf("%s…%s", string(runes[:halfs]), string(runes[(length-halfs):]))
		},
	}

	tm.Init()

	return tm
}
//NewBaseHandler is the BaseHandler constructor
func NewBaseHandler(l *logrus.Logger, c *app.Config, tpls map[string]*template.Template, cookieHandler *securecookie.SecureCookie) *BaseHandler {
	return &BaseHandler{Logr: l, Config: c, Templates: tpls, bufpool: bpool.NewBufferPool(64), cookieH: cookieHandler}
}
Esempio n. 18
0
package app

import (
	"html/template"
	"log"
	"net/http"

	"github.com/oxtoacart/bpool"
)

var bufpool = bpool.NewBufferPool(64)

var templateMap = map[string]*template.Template{
	"url-index":         createTemplate("templates/base.html", "templates/url-index.html"),
	"url-new":           createTemplate("templates/base.html", "templates/url-new.html"),
	"url-view":          createTemplate("templates/base.html", "templates/url-view.html"),
	"url-edit":          createTemplate("templates/base.html", "templates/url-edit.html"),
	"tag-index":         createTemplate("templates/base.html", "templates/tag-index.html"),
	"settings":          createTemplate("templates/base.html", "templates/settings.html"),
	"shitbucket-import": createTemplate("templates/base.html", "templates/shitbucket-import.html"),
	"registration":      createTemplate("templates/config-base.html", "templates/register.html"),
	"login":             createTemplate("templates/config-base.html", "templates/login.html"),
	"404":               createTemplate("templates/config-base.html", "templates/404.html"),
}

var templateFuncs = template.FuncMap{
	"reverse":    reverse,
	"isyoutube":  isYoutube,
	"youtubevid": youtubevid,
	"newcontext": newcontext,
}
Esempio n. 19
0
	"github.com/Unknwon/com"
	"github.com/gernest/zedlist/modules/tmpl"

	userAuth "github.com/gernest/zedlist/middlewares/auth"
	"github.com/gernest/zedlist/middlewares/flash"
	"github.com/gernest/zedlist/middlewares/i18n"
	"github.com/gernest/zedlist/routes/auth"
	"github.com/labstack/echo"
	"github.com/oxtoacart/bpool"
)

var ts = testServer()
var client = &http.Client{Jar: getJar()}
var dashPath = fmt.Sprintf("%s/dash", ts.URL)
var bufPool = bpool.NewBufferPool(10)

func testServer() *httptest.Server {
	e := echo.New()
	e.SetRenderer(tmpl.NewRenderer())

	// middlewares
	e.Use(i18n.Langs())      // languages
	e.Use(flash.Flash())     // flash messages
	e.Use(userAuth.Normal()) // adding user context data

	// BASE

	// DASHBOARD
	d := e.Group("/dash")
	d.Get("/", Home)
//NewBaseHandler is the BaseHandler constructor
func NewBaseHandler(l *logrus.Logger, c *app.Config) *BaseHandler {
	return &BaseHandler{Logr: l, Config: c, bufpool: bpool.NewBufferPool(64)}
}
Esempio n. 21
0
	"strings"
	"sync"
	"sync/atomic"

	"github.com/getlantern/errors"
	"github.com/getlantern/hidden"
	"github.com/getlantern/ops"
	"github.com/oxtoacart/bpool"
)

var (
	outs           atomic.Value
	reporters      []ErrorReporter
	reportersMutex sync.RWMutex

	bufferPool = bpool.NewBufferPool(200)
)

func init() {
	ResetOutputs()
}

func SetOutputs(errorOut io.Writer, debugOut io.Writer) {
	outs.Store(&outputs{
		ErrorOut: errorOut,
		DebugOut: debugOut,
	})
}

func ResetOutputs() {
	SetOutputs(os.Stderr, os.Stdout)
Esempio n. 22
0
import (
	"bytes"
	"encoding/json"
	"log"
	"os"
	"runtime"

	"github.com/oxtoacart/bpool"
)

var (
	MaxWorker = runtime.NumCPU() * 2
	MaxQueue  = os.Getenv("MAX_QUEUE")
)

var bufpool = bpool.NewBufferPool(1024)

// Job represents the job to be run
type Job struct {
	raw   interface{}
	outch chan Result
}

type Result struct {
	data    *bytes.Buffer
	bufpool *bpool.BufferPool
}

func (j *Job) MarshalData() {

	result := Result{