Ejemplo n.º 1
0
func init() {
	ALL_METHODS = []string{GET, HEAD, POST, CONNECT, DELETE, OPTIONS, PUT, TRACE}

	defaultMimeTypes = make(map[string]string)
	defaultMimeTypes[".htm"] = MIME_TYPE_HTML
	defaultMimeTypes[".html"] = MIME_TYPE_HTML
	defaultMimeTypes[".xhtml"] = MIME_TYPE_XHTML_XML
	defaultMimeTypes[".xml"] = MIME_TYPE_XML
	defaultMimeTypes[".css"] = MIME_TYPE_CSS
	defaultMimeTypes[".js"] = MIME_TYPE_JAVASCRIPT
	defaultMimeTypes[".json"] = MIME_TYPE_JSON
	defaultMimeTypes[".jpg"] = MIME_TYPE_JPEG
	defaultMimeTypes[".jpeg"] = MIME_TYPE_JPEG
	defaultMimeTypes[".gif"] = MIME_TYPE_GIF
	defaultMimeTypes[".png"] = MIME_TYPE_PNG
	defaultMimeTypes[".ico"] = MIME_TYPE_ICO
	defaultMimeTypes[".swf"] = MIME_TYPE_SWF
	defaultMimeTypes[".zip"] = MIME_TYPE_ZIP
	defaultMimeTypes[".bz2"] = MIME_TYPE_BZIP2
	defaultMimeTypes[".gz"] = MIME_TYPE_GZ
	defaultMimeTypes[".tar"] = MIME_TYPE_TAR
	defaultMimeTypes[".tgz"] = MIME_TYPE_GZ
	defaultMimeTypes[".htc"] = MIME_TYPE_COMPONENT
	defaultMimeTypes[".manifest"] = MIME_TYPE_CACHE_MANIFEST
	defaultMimeTypes[".svg"] = MIME_TYPE_SVG
	defaultMimeTypes[".txt"] = MIME_TYPE_TEXT_PLAIN
	defaultMimeTypes[".text"] = MIME_TYPE_TEXT_PLAIN
	defaultMimeTypes[".csv"] = MIME_TYPE_CSV

	var err error
	HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err = template.New("directory_listing_success").Parse(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE_STRING)
	template.Must(HTML_DIRECTORY_LISTING_SUCCESS_TEMPLATE, err)
	HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err = template.New("directory_listing_error").Parse(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE_STRING)
	template.Must(HTML_DIRECTORY_LISTING_ERROR_TEMPLATE, err)
}
Ejemplo n.º 2
0
func InitAdminTemplates() {
	serverPage = template.Must(template.ParseFiles("views/admin/templates/server.html"))
	banlogsTempl = template.Must(template.ParseFiles("views/admin/templates/ban_logs.html"))
	chatLogsTempl = template.Must(template.ParseFiles("views/admin/templates/chatlogs.html"))
	lobbiesTempl = template.Must(template.ParseFiles("views/admin/templates/lobbies.html"))
	adminPageTempl = template.Must(template.ParseFiles("views/admin/index.html"))
}
Ejemplo n.º 3
0
func (c *Controller) Login() (string, error) {

	var pool_tech_works int

	funcMap := template.FuncMap{
		"noescape": func(s string) template.HTML {
			return template.HTML(s)
		},
	}

	data, err := static.Asset("static/templates/login.html")
	if err != nil {
		return "", err
	}
	modal, err := static.Asset("static/templates/modal.html")
	if err != nil {
		return "", err
	}

	t := template.Must(template.New("template").Funcs(funcMap).Parse(string(data)))
	t = template.Must(t.Parse(string(modal)))

	b := new(bytes.Buffer)

	// есть ли установочный пароль и был ли начально записан ключ
	var setupPassword bool
	if !c.Community {
		setupPassword_, err := c.Single("SELECT setup_password FROM config").String()
		if err != nil {
			return "", err
		}
		myKey, err := c.GetMyPublicKey(c.MyPrefix)
		if err != nil {
			return "", err
		}
		if len(myKey) == 0 && (len(setupPassword_) > 0 || setupPassword_ == string(utils.DSha256(""))) {
			setupPassword = true
		}
	}
	//fmt.Println(c.Lang)
	// проверим, не идут ли тех. работы на пуле
	if len(c.NodeConfig["pool_admin_user_id"]) > 0 && c.NodeConfig["pool_admin_user_id"] != utils.Int64ToStr(c.UserId) && c.NodeConfig["pool_tech_works"] == "1" && c.Community {
		pool_tech_works = 1
	} else {
		pool_tech_works = 0
	}
	err = t.ExecuteTemplate(b, "login", &loginStruct{
		Lang:          c.Lang,
		MyModalIdName: "myModalLogin",
		UserID:        c.UserId,
		PoolTechWorks: pool_tech_works,
		SetupPassword: setupPassword,
		Community:     c.Community,
		Desktop:       utils.Desktop(),
		Mobile:        utils.Mobile()})
	if err != nil {
		return "", err
	}
	return b.String(), nil
}
func init() {
	http.HandleFunc("/", authOnly(root))
	http.HandleFunc("/sign", authOnly(sign))

	guestbookTemplate = template.Must(template.ParseFiles("tmpl/index.tmpl"))
	signinTemplate = template.Must(template.ParseFiles("tmpl/signin.tmpl"))
}
Ejemplo n.º 5
0
func TestTemplate_FuncMap_url(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "root"}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "user" 713}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/user/713"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %v, but %v", expected, actual)
		}
	}()
}
Ejemplo n.º 6
0
func TestRender(t *testing.T) {
	driverNames := [...]string{"file", "memory"}

	for _, v := range driverNames {
		d, err := render.New(v, map[string]string{
			"dir": "./_testdata",
		})
		if err != nil {
			t.Fatal(err)
		}

		d.AddCommonTpl("base.html")
		tpl := template.Must(d.GetTemplate("index.html"))

		buf := &bytes.Buffer{}

		tpl.Execute(buf, map[string]string{
			"Title":   "标题",
			"Content": "内容",
		})

		if testdata1 != buf.String() {
			t.Fatalf("Content not equal %q", v)
		}

		_ = template.Must(d.GetTemplate("index1.html"))
	}

}
Ejemplo n.º 7
0
func CompileUserTemplates() {
	usersTemplates = template.Must(layout.Clone()).Funcs(template.FuncMap{
		"sliceBy12": func(problems []models.Problem) [][]models.Problem {
			slices := make([][]models.Problem, 0, len(problems)/12+1)

			for i := 0; i+11 < len(problems); i += 12 {
				slice := make([]models.Problem, 12)
				for j := i; j < i+12; j++ {
					slice[j] = problems[i+j]
				}
				slices = append(slices, slice)
			}

			if len(problems)%12 != 0 {
				slice := make([]models.Problem, len(problems)%12)
				for i := 0; i < len(problems)%12; i++ {
					slice[i] = problems[len(problems)-len(problems)%12+i]
				}
				slices = append(slices, slice)
			}

			return slices
		},
	})
	usersTemplates = template.Must(usersTemplates.ParseGlob("./templates/users/*.html"))
}
Ejemplo n.º 8
0
// Handle errors here, this allows us to control the format of the output rather
// than using http.Error() defaults
func errorHandler(w http.ResponseWriter, r *http.Request, status int, err string) {
	w.WriteHeader(status)
	switch status {
	case http.StatusNotFound:
		logHandler("ERROR", fmt.Sprintf("client %s tried to request %v", r.RemoteAddr, r.URL.Path))
		page := template.Must(template.ParseFiles(
			"static/_base.html",
			"static/404.html",
		))

		if err := page.Execute(w, nil); err != nil {
			errorHandler(w, r, http.StatusInternalServerError, err.Error())
			return
		}
	case http.StatusInternalServerError:
		logHandler("ERROR", fmt.Sprintf("an internal server error occured when %s requested %s with error:\n%s", r.RemoteAddr, r.URL.Path, err))
		page := template.Must(template.ParseFiles(
			"static/_base.html",
			"static/500.html",
		))

		if err := page.Execute(w, nil); err != nil {
			// IF for some reason the tempalets for 500 errors fails, fallback
			// on http.Error()
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
Ejemplo n.º 9
0
func serveCmd() {
	var err error

	// load and parse templates
	baseTmplPath := *templatePath + "/base.html"
	tmplHome = template.Must(template.ParseFiles(*templatePath+"/home.html", baseTmplPath))
	tmplAccount = template.Must(template.ParseFiles(*templatePath+"/account.html", baseTmplPath))
	//tmplLogout = template.Must(template.ParseFiles(*templatePath+"/logout.html", baseTmplPath))
	//tmplNewUser = template.Must(template.ParseFiles(*templatePath+"/newuser.html", baseTmplPath))
	tmplUser = template.Must(template.ParseFiles(*templatePath+"/user.html", baseTmplPath))
	tmplBomView = template.Must(template.ParseFiles(*templatePath+"/bom_view.html", baseTmplPath))
	tmplBomUpload = template.Must(template.ParseFiles(*templatePath+"/bom_upload.html", baseTmplPath))
	if err != nil {
		log.Fatal(err)
	}

	openBomStore()
	openAuthStore()
	openPricingSource()

	// serve template static assets (images, CSS, JS)
	http.Handle("/static/", http.FileServer(http.Dir(*templatePath+"/")))
	http.Handle("/favicon.ico", http.FileServer(http.Dir(*templatePath+"/static/")))

	// fall through to default handler
	http.HandleFunc("/", baseHandler)

	listenString := fmt.Sprintf("%s:%d", *listenHost, *listenPort)
	http.ListenAndServe(listenString, nil)
	fmt.Println("Serving at " + listenString)
}
Ejemplo n.º 10
0
func init() {
	layout, err := ioutil.ReadFile("templates/layout.html")
	if err != nil {
		log.Fatal("Could not read layout:", err)
	}
	files, err := filepath.Glob("templates/*")
	if err != nil {
		log.Fatal("Could not glob templates:", err)
	}

	for _, f := range files {
		if filepath.Base(f) == "layout.html" {
			continue
		}
		content, err := ioutil.ReadFile(f)
		if err != nil {
			log.Fatalf("Could not read %q: %v", f, err)
		}

		t := template.New("page")
		t.Funcs(map[string]interface{}{
			"toEuros": func(x int) float64 {
				return float64(x) / 100
			},
		})

		t = template.Must(t.Parse(string(layout)))
		template.Must(t.New("content").Parse(string(content)))

		parsedTemplates[filepath.Base(f)] = t
	}
}
Ejemplo n.º 11
0
func errorHandler(w http.ResponseWriter, r *http.Request, status int, err string) {
	w.WriteHeader(status)
	page := template.Must(template.ParseFiles(
		"static/_base.html",
		"static/baseError.html",
	))

	switch status {
	case http.StatusNotFound:
		page = template.Must(template.ParseFiles(
			"static/_base.html",
			"static/404.html",
		))
	case http.StatusInternalServerError:
		page = template.Must(template.ParseFiles(
			"static/_base.html",
			"static/500.html",
		))
	case http.StatusUnauthorized:
		page = template.Must(template.ParseFiles(
			"static/_base.html",
			"static/401.html",
		))
	}

	if err := page.Execute(w, nil); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Ejemplo n.º 12
0
func reports(c *appcontext.AppContext, w http.ResponseWriter, r *http.Request) (int, error) {

	SetCache(w, 60*60)

	report := r.FormValue("report")
	var (
		p   Page
		err error
	)

	if report == "items" || report == "" {
		templates.Templates = template.Must(template.ParseFiles("templates/reports/items.html", "templates/reports.html", templates.LayoutPath))
		err = templates.Templates.ExecuteTemplate(w, "base", p)
	} else if report == "itemTrends" {
		templates.Templates = template.Must(template.ParseFiles("templates/reports/itemTrends.html", "templates/reports.html", templates.LayoutPath))
		err = templates.Templates.ExecuteTemplate(w, "base", p)
	} else if report == "telVar" {
		templates.Templates = template.Must(template.ParseFiles("templates/reports/telVar.html", "templates/reports.html", templates.LayoutPath))
		err = templates.Templates.ExecuteTemplate(w, "base", p)
	} else if report == "ap" {
		templates.Templates = template.Must(template.ParseFiles("templates/reports/ap.html", "templates/reports.html", templates.LayoutPath))
		err = templates.Templates.ExecuteTemplate(w, "base", p)
	} else if report == "guilds" {
		templates.Templates = template.Must(template.ParseFiles("templates/reports/guilds.html", "templates/reports.html", templates.LayoutPath))
		err = templates.Templates.ExecuteTemplate(w, "base", p)
	}

	if err != nil {
		return http.StatusInternalServerError, err
	}

	return http.StatusOK, nil
}
Ejemplo n.º 13
0
// checkEnvironment checks if required dirs and files exist, uses defaults if not.
func checkEnvironment() {
	_, err := os.Stat(dataDir)
	if err != nil {
		if os.IsNotExist(err) {
			err = os.Mkdir(dataDir, 0644)
			if err != nil {
				fmt.Println(`Unable to create "notes" directory:`, err)
				os.Exit(0)
			}
		} else {
			fmt.Println(`Unable to check existence of "notes" directory:`, err)
			os.Exit(0)
		}
	}
	_, err = os.Stat(templatesDir)
	if err != nil {
		if os.IsNotExist(err) {
			// Template dir does not exist
			fmt.Println("Using default templates.")
			templates = template.Must(template.New("index.html").Parse(defaultTemplateIndexHtml))
			template.Must(templates.New("view.html").Parse(defaultTemplateViewHtml))
			template.Must(templates.New("edit.html").Parse(defaultTemplateEditHtml))
			template.Must(templates.New("error.html").Parse(defaultTemplateErrorHtml))
		}
	} else {
		fmt.Println("Using file templates.")
		templates = template.Must(template.ParseFiles(
			templatesDir+"index.html",
			templatesDir+"view.html",
			templatesDir+"edit.html",
			templatesDir+"error.html"))
	}
}
Ejemplo n.º 14
0
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	tmpl := template.New("base")
	template.Must(tmpl.Parse(BaseTmpl))
	template.Must(tmpl.Parse(ConfigTemp))
	nodes := GetScattrData()
	tmpl.Execute(w, nodes)
}
Ejemplo n.º 15
0
func viewHandler(w http.ResponseWriter, r *http.Request) {
	entries := Store.AllEntries()
	tmpl := template.New("base")
	template.Must(tmpl.Parse(BaseTmplStr))
	template.Must(tmpl.Parse(ViewTmplStr))
	tmpl.Execute(w, entries)
}
Ejemplo n.º 16
0
func FindHandler(rw http.ResponseWriter, req *http.Request) {
	var _, er = req.Cookie("fishme")

	if er != nil {
		http.Redirect(rw, req, "/", http.StatusFound)
	} else {
		term := req.FormValue("find")
		if term != "" {
			term = strings.ToLower(term)
			term = strings.Replace(term, term[:1], strings.ToUpper(term[:1]), 1)
			log.Println(term)

			temp, err := template.ParseFiles("template/find.html")
			utility.ShitAppend(err)

			temp = template.Must(temp.Parse(ParseNavbarFile("template/navbar"))) // Add The content of the navbar.tmpl to the current template
			temp = template.Must(temp.ParseFiles("template/add_fish.tmpl"))
			temp = template.Must(temp.ParseFiles("template/map.tmpl")) // Map template

			fishFind := FindFish(term)

			temp.Execute(rw, ParseSecureFishFile(fishFind))
		} else {
			http.Redirect(rw, req, "/home", http.StatusFound)
		}

	}
}
Ejemplo n.º 17
0
func compileTemplate(name string) *template.Template {
	t := template.New(name)
	t = template.Must(t.Funcs(funcMap).ParseGlob("www/views/layouts/*.html"))
	t.Delims("#{", "}#")

	return template.Must(t.ParseFiles("www/views/" + name + ".html"))
}
Ejemplo n.º 18
0
// Main entry point
func main() {

	// Connect to DB
	dbConn = dbConnect()
	defer dbConn.Close()

	// Parse initial flags
	flag.Parse()

	// Define home template and hub
	homeTempl = template.Must(template.ParseFiles(filepath.Join(templatesPath, "map.html")))
	routesTempl = template.Must(template.ParseFiles(filepath.Join(templatesPath, "routes.html")))
	h := newHub()

	// Run hub concurrently
	go h.runHub()

	// Define handlers
	http.HandleFunc("/", homeHandler)
	http.Handle("/ws", wsHandler{h: h})
	http.Handle("/routes/ws", wsHandler{h: h})
	http.HandleFunc("/routes/", routeSimulatorHandler)
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(httpStaticPath))))

	// Start server
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
Ejemplo n.º 19
0
// Sends email based on the result of all batches
func (r *GlobalResults) sendMail() {

	funcMap := template.FuncMap{
		"odd": func(i int) bool { return i%2 == 0 },
	}

	tHeader := template.Must(template.New("header").Parse(emailTemplateHtmlHeader))
	tBody := template.Must(template.New("body").Funcs(funcMap).Parse(emailTemplateHtmlBody))

	var docHeader bytes.Buffer
	tHeader.Execute(&docHeader, r.Author)

	for _, br := range r.BatchResultList {
		var docBody bytes.Buffer

		tBody.Execute(&docBody, br)

		TraceActivity.Printf("----------------------------------------------------------------------------- \n")
		TraceActivity.Printf("GeneratedCOntent : \n")
		TraceActivity.Printf("%s\n", docBody.String())
		TraceActivity.Printf("----------------------------------------------------------------------------- \n")

		var buffer bytes.Buffer
		buffer.WriteString(docHeader.String())
		buffer.WriteString(docBody.String())
		br.Smtp.sendEmailHtml(br, buffer.String())
	}
}
Ejemplo n.º 20
0
func init() {
	if templates == nil {
		templates = make(map[string]*template.Template)
	}
	templates["index"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index.tmpl"))
	templates["index1"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/index1.tmpl"))
	templates["edit"] = template.Must(template.ParseFiles("tmpl/base.tmpl", "tmpl/edit.tmpl"))
	templates["preview"] = template.Must(template.ParseFiles("tmpl/preview.tmpl"))

	//handle image/css and generated html files
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
	http.Handle("/_images/", http.StripPrefix("/_images/", http.FileServer(http.Dir("_images"))))
	http.Handle("/_html/", http.StripPrefix("/_html/", http.FileServer(http.Dir("_html"))))
	http.Handle("/_html/_images/", http.StripPrefix("/_html/_images/", http.FileServer(http.Dir("_html/_images"))))
	http.Handle("/_html/css", http.StripPrefix("/_html/css", http.FileServer(http.Dir("_html/css"))))

	// set up html options
	htmlExt = 0
	htmlExt |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
	htmlExt |= blackfriday.EXTENSION_TABLES
	htmlExt |= blackfriday.EXTENSION_FENCED_CODE
	htmlExt |= blackfriday.EXTENSION_AUTOLINK
	htmlExt |= blackfriday.EXTENSION_STRIKETHROUGH
	htmlExt |= blackfriday.EXTENSION_SPACE_HEADERS

	htmlFlags = blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES |
		blackfriday.HTML_FOOTNOTE_RETURN_LINKS |
		blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES

}
Ejemplo n.º 21
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
	}
}
Ejemplo n.º 22
0
func init() {
	Router.Get("/_ah/cron/search", appstats.NewHandler(ahCronSearchHandler))
	Router.Get("/_ah/status", appstats.NewHandler(ahStatusHandler))
	Router.Get("/_ah/", appstats.NewHandler(ahHandler))

	Router.Get("/debug/prepare_test", appstats.NewHandler(debugPrepareTestHandler))

	Router.Get("/-/about", appstats.NewHandler(aboutHandler))
	Router.Get("/-/doc", appstats.NewHandler(docHandler))
	Router.Get("/-/doc/:section", appstats.NewHandler(docHandler))
	Router.Get("/-/me", appstats.NewHandler(myHandler))
	Router.Post("/-/me/register", appstats.NewHandler(registerHandler))
	Router.Get("/-/me/generate", appstats.NewHandler(generateHandler))
	Router.Post("/-/me/openid", appstats.NewHandler(openIdHandler))
	Router.Get("/-/nuts", appstats.NewHandler(nutsHandler))

	Router.Put("/:vendor/:name/:version", appstats.NewHandler(nutCreateHandler))
	Router.Get("/:vendor/:name/:version", appstats.NewHandler(nutShowHandler))
	Router.Get("/:vendor/:name", appstats.NewHandler(nutShowHandler))
	Router.Get("/:vendor", appstats.NewHandler(nutsHandler))

	Router.Get("/", appstats.NewHandler(welcomeHandler))

	http.Handle("/", Router)

	Base = template.Must(template.ParseFiles("gonuts/templates/base.html"))
	template.Must(Base.ParseGlob("gonuts/templates/base/*.html"))
}
Ejemplo n.º 23
0
func treeOperations(w http.ResponseWriter, r *http.Request) {

	if r.Method == "POST" {
		err := r.ParseForm()
		if err != nil {
			io.WriteString(w, fmt.Sprintf("Error parsing the submitted form:\n%s", err))
		}

		var v int
		v, err = strconv.Atoi(r.Form["number"][0])
		if err != nil {
			io.WriteString(w, fmt.Sprintf("Error parsing the given number:\n%s", err))
		}

		if r.Form["insert"] != nil {

			fmt.Printf("\nInserting [%d]\n", v)
			btree = Insert(btree, v)

		} else if r.Form["delete"] != nil {

			fmt.Printf("\nDeleting [%d]\n", v)
			btree = Delete(btree, v)

		} else {
			io.WriteString(w, "Neither an insert request, nor a delete request")
			return
		}

		renderer := PrintbTree(btree, r.Form["numbers"][0])

		err =
			template.Must(template.ParseFiles("treedisplay.html")).Execute(w, &renderer)
		if err != nil {
			io.WriteString(w, fmt.Sprintf("Error generating HTML file from the template:\n%s", err))
			return
		}
	} else {
		/* The next if loop is a hack to avoid re-initialization due to
		 * the GET request that will come when the page gets rendered
		 * during the response of the POST (the above block) */
		if btree == nil {
			btree, _ = InitializebTree(3)
			fmt.Println("Initializing the btree")

			for _, v := range []int{6, 1, 3, 10, 4, 7, 8, 9, 18, 12, 13,
				19, 15, 22, 33, 35, 44, 70, 37, 38, 39, 50, 60, 55, 80,
				90, 101, 102, 100, 110, 120, 57, 58} {
				btree = Insert(btree, v)
			}
			renderer := PrintbTree(btree, "")
			err :=
				template.Must(template.ParseFiles("treedisplay.html")).Execute(w, &renderer)
			if err != nil {
				io.WriteString(w, fmt.Sprintf("Error generating HTML file from the template:\n%s", err))
				return
			}
		}
	}
}
Ejemplo n.º 24
0
func init() {
	t = make(map[string]*template.Template)
	temp := template.Must(template.ParseFiles("base.html", "user.html"))
	t["user.html"] = temp
	temp = template.Must(template.ParseFiles("base.html", "page.html"))
	t["page.html"] = temp
}
Ejemplo n.º 25
0
// Login template
func (ctrl *Access) Login(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		t := template.Must(template.ParseFiles("views/layouts/application.htm", "views/login/login.htm"))

		if err := t.Execute(w, &Access{}); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else {
		r.ParseForm()

		user := ctrl.Auth(r.Form["username"][0], r.Form["password"][0])
		if user != nil {
			t := template.Must(template.ParseFiles("views/layouts/application.htm", "views/login/info.htm"))

			page := &Access{LoginPage: &LoginPage{UserName: r.Form["username"][0], HasVideoAccess: user.HasVideoAccess}}
			if err := t.Execute(w, page); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

		} else {
			http.Error(w, "Auth", http.StatusForbidden)
		}
	}
}
Ejemplo n.º 26
0
func LoadTemplates() {
	EmailTmpl = text_template.Must(text_template.New("Email").ParseGlob(
		filepath.Join(cfg.TemplatesDir, "email", "*.txt"),
	))

	SignupTmpl = template.Must(template.New("Signup").ParseFiles(
		filepath.Join(cfg.TemplatesDir, "account", "base.html"),
		filepath.Join(cfg.TemplatesDir, "account", "signup.html"),
	))

	SignupOkTmpl = template.Must(template.New("SignupOk").ParseFiles(
		filepath.Join(cfg.TemplatesDir, "account", "base.html"),
		filepath.Join(cfg.TemplatesDir, "account", "signup_ok.html"),
	))

	HelloTmpl = template.Must(template.New("Hello").ParseFiles(
		filepath.Join(cfg.TemplatesDir, "account", "base.html"),
		filepath.Join(cfg.TemplatesDir, "account", "hello.html"),
	))

	LoginTmpl = template.Must(template.New("Login").ParseFiles(
		filepath.Join(cfg.TemplatesDir, "account", "base.html"),
		filepath.Join(cfg.TemplatesDir, "account", "login.html"),
	))
}
Ejemplo n.º 27
0
// HTTPServer is the constructor of the HTTP server
func HTTPServer(redis *redisobj, cache *Cache) *HTTP {
	h := new(HTTP)
	h.redis = redis
	h.geoip = NewGeoIP()
	h.templates.mirrorlist = template.Must(h.LoadTemplates("mirrorlist"))
	h.templates.mirrorstats = template.Must(h.LoadTemplates("mirrorstats"))
	h.cache = cache
	h.stats = NewStats(redis)
	h.engine = DefaultEngine{}
	http.Handle("/", NewGzipHandler(h.requestDispatcher))

	// Load the GeoIP database
	if err := h.geoip.LoadGeoIP(); err != nil {
		log.Critical("Can't load the GeoIP databases: %v", err)
		if len(GetConfig().Fallbacks) > 0 {
			log.Warning("All requests will be served by the backup mirrors!")
		} else {
			log.Error("Please configure fallback mirrors!")
		}
	}

	// Initialize the random number generator
	rand.Seed(time.Now().UnixNano())
	return h
}
Ejemplo n.º 28
0
func TestTemplateFuncs_url(t *testing.T) {
	oldAppConfig := appConfig
	appConfig = newTestAppConfig()
	defer func() {
		appConfig = oldAppConfig
	}()
	tmpl := template.Must(template.New("test").Funcs(TemplateFuncs).Parse(`{{url "root"}}`))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err != nil {
		panic(err)
	}
	actual := buf.String()
	expected := "/"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %q, but %q", expected, actual)
	}

	tmpl = template.Must(template.New("test").Funcs(TemplateFuncs).Parse(`{{url "user" 713}}`))
	buf.Reset()
	if err := tmpl.Execute(&buf, nil); err != nil {
		panic(err)
	}
	actual = buf.String()
	expected = "/user/713"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %v, but %v", expected, actual)
	}
}
Ejemplo n.º 29
0
func TestTemplateFuncs_date(t *testing.T) {
	base := `{{date . "%v"}}`
	now := time.Now()
	tmpl := template.Must(template.New("test").Funcs(TemplateFuncs).Parse(fmt.Sprintf(base, "2006/01/02 15:04:05.999999999")))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, now); err != nil {
		panic(err)
	}
	actual := buf.String()
	expected := now.Format("2006/01/02 15:04:05.999999999")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %q, but %q", expected, actual)
	}

	tmpl = template.Must(template.New("test").Funcs(TemplateFuncs).Parse(fmt.Sprintf(base, "Jan 02 2006 03:04.999999999")))
	buf.Reset()
	if err := tmpl.Execute(&buf, now); err != nil {
		panic(err)
	}
	actual = buf.String()
	expected = now.Format("Jan 02 2006 03:04.999999999")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %q, but %q", expected, actual)
	}
}
Ejemplo n.º 30
0
func NewRuleHandler(w http.ResponseWriter, r *http.Request) {
	rule := NewRule("", defaultJs, []string{""})
	tmpl := template.New("base")
	template.Must(tmpl.Parse(BaseTemplateStr))
	template.Must(tmpl.Parse(NewTemplateStr))
	tmpl.Execute(w, rule)

}