Golang ParseGlob示例

说明

golang parseglob示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: html/template

示例#1
文件: web.go 项目: sugaofeng/platform

func watchAndParseTemplates() {

	templatesDir := utils.FindDir("web/templates")
	l4g.Debug(utils.T("web.parsing_templates.debug"), templatesDir)
	var err error
	if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
		l4g.Error(utils.T("web.parsing_templates.error"), err)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		l4g.Error(utils.T("web.create_dir.error"), err)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					l4g.Info(utils.T("web.reparse_templates.info"), event.Name)
					if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
						l4g.Error(utils.T("web.parsing_templates.error"), err)
					}
				}
			case err := <-watcher.Errors:
				l4g.Error(utils.T("web.dir_fail.error"), err)
			}
		}
	}()

	err = watcher.Add(templatesDir)
	if err != nil {
		l4g.Error(utils.T("web.watcher_fail.error"), err)
	}
}

示例#2
文件: web.go 项目: jianyongchen/platform

func watchAndParseTemplates() {

	templatesDir := utils.FindDir("web/templates")
	l4g.Debug("Parsing templates at %v", templatesDir)
	var err error
	if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
		l4g.Error("Failed to parse templates %v", err)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		l4g.Error("Failed to create directory watcher %v", err)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					l4g.Info("Re-parsing templates because of modified file %v", event.Name)
					if Templates, err = template.ParseGlob(templatesDir + "*.html"); err != nil {
						l4g.Error("Failed to parse templates %v", err)
					}
				}
			case err := <-watcher.Errors:
				l4g.Error("Failed in directory watcher %v", err)
			}
		}
	}()

	err = watcher.Add(templatesDir)
	if err != nil {
		l4g.Error("Failed to add directory to watcher %v", err)
	}
}

示例#3
文件: gin.go 项目: jakerandell/wedding

func (engine *Engine) LoadHTMLGlob(pattern string) {
	if IsDebugging() {
		debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))
		engine.HTMLRender = render.HTMLDebug{Glob: pattern}
	} else {
		templ := template.Must(template.ParseGlob(pattern))
		engine.SetHTMLTemplate(templ)
	}
}

示例#4
文件: webserver.go 项目: alouca/gosyslog

func startServer(port string) {
	manager = session.NewSessionManager(nil)

	manager.OnStart(func(session *session.Session) {
		l.Debug("Session Manager: Started a new session.\n")
	})
	manager.OnEnd(func(session *session.Session) {
		l.Debug("Session Manager: Destroyed a session.\n")
	})
	manager.SetTimeout(10)

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static/"))))
	http.HandleFunc("/data", DataHandler)
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/login", LoginHandler)
	var e error

	t, e = template.ParseGlob("web/templates/*.tmpl")

	if e != nil {
		l.Fatal("Unable to parse templates: %s\n", e.Error())
	}

	e = http.ListenAndServe(port, nil)

	if e != nil {
		l.Fatal("Unable to start embeeded webserver: %s\n", e.Error())
	}
}

示例#5
文件: main.go 项目: jgtaruc/GoLang130

func init() {
	tpl, _ = template.ParseGlob("*.html")
	http.HandleFunc("/", main)

	//serve the css files in a file server instead of uploading it to gcs and querying it.
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css"))))
}

示例#6
文件: main.go 项目: Oralordos/Digitalocean-Golang-and-Aerospike

func main() {
	tpl = template.Must(template.ParseGlob("templates/*.gohtml"))

	f, err := os.OpenFile("logfile.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0664)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	log.SetOutput(f)

	client, err = as.NewClient("127.0.0.1", 3000)
	if err != nil {
		panic(err)
	}
	defer client.Close()

	router := httprouter.New()
	router.GET("/", index)
	router.GET("/login", loginPage)
	router.POST("/login", login)
	router.GET("/logout", logout)
	router.GET("/create", createPage)
	router.POST("/create", create)
	err = http.ListenAndServe(":9000", router)
	if err != nil {
		panic(err)
	}
}

示例#7
文件: template.go 项目: orian/template

func ParseGlob(pattern string) (Template, error) {
	if Debug {
		return (&reloadTemplate{}).ParseGlob(pattern)
	}
	t, err := htmlTmpl.ParseGlob(pattern)
	return &instantTemplate{t}, err
}

示例#8
文件: auth.go 项目: topiary-io/topiary

func adminUsersHandler(w http.ResponseWriter, r *http.Request, admin Location) {
	isAuth(w, r, admin, "admin")
	if r.Method == "POST" {
		var user httpauth.UserData
		user.Username = r.PostFormValue("username")
		user.Email = r.PostFormValue("email")
		password := r.PostFormValue("password")
		user.Role = r.PostFormValue("role")
		if err := aaa.Register(w, r, user, password); err != nil {
			// maybe something
		}
	}

	if user, err := aaa.CurrentUser(w, r); err == nil {
		type data struct {
			User  httpauth.UserData
			Roles map[string]httpauth.Role
			Users []httpauth.UserData
			Msg   []string
		}
		messages := aaa.Messages(w, r)
		users, err := backend.Users()
		if err != nil {
			panic(err)
		}
		d := data{User: user, Roles: roles, Users: users, Msg: messages}
		var templates = template.Must(template.ParseGlob("admin/templates/*"))
		t_err := templates.ExecuteTemplate(w, "manage-accounts.html", d)
		if t_err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

示例#9
文件: util.go 项目: asadovsky/tadue

// Wraps other http handlers. Creates context object, recovers from panics, etc.
func WrapHandlerImpl(fn AppHandlerFunc, parseForm bool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		c := &Context{}

		// See http://blog.golang.org/2010/08/defer-panic-and-recover.html.
		defer func() {
			if data := recover(); data != nil {
				c.Aec().Errorf(fmt.Sprint(data))
				ServeError(w, data)
			}
		}()

		// Initialize the request context object.
		c.SetAec(appengine.NewContext(r))
		CheckError(ReadSession(r, c))
		if msg, err := ConsumeFlash(w, r); err != nil && err != http.ErrNoCookie {
			ServeError(w, err)
			return
		} else {
			c.SetFlash(msg)
		}

		if parseForm {
			CheckError(r.ParseForm())
		}

		if appengine.IsDevAppServer() {
			tmpl = template.Must(template.ParseGlob("templates/*.html"))
			text_tmpl = text_template.Must(text_template.ParseGlob("templates/*.txt"))
		}
		fn(w, r, c)
	}
}

示例#10
文件: main.go 项目: ljmeyers80529/CSCI130

// set everything up.
func init() {
	tpl = template.Must(template.ParseGlob("*.html"))
	resourceHandler("css")
	resourceHandler("img")
	resourceHandler("photos")
	http.HandleFunc("/", mainPage)
}

示例#11
文件: actions.go 项目: DeyV/go-newsagg

func actionHome(w http.ResponseWriter, req *http.Request) {

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}

示例#12
文件: templates.go 项目: billyboar/GCSolutions

func loadTemplates() (templates *template.Template, err error) {
	if !*devMode && t != nil {
		return t, nil
	}
	t, err = template.ParseGlob("templates/*")
	return t, err
}

示例#13
文件: server.go 项目: rdallman/aumdug-web

//reload templates on modify
func listenForChanges() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	done := make(chan bool)

	// Process events
	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				log.Println("event:", ev)
				//recompile templates
				templates = template.Must(template.ParseGlob("templates/*.html"))
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Watch("templates/")
	if err != nil {
		log.Fatal(err)
	}

	<-done

	watcher.Close()
}

示例#14
文件: post_controller.go 项目: skyec/esblog

func helperMustLoadTemplates() *template.Template {
	t, err := template.ParseGlob(config.resourceDir + "/views/posts/*.html")
	if err != nil {
		panic(err.Error())
	}
	return t
}

示例#15
文件: nisepost.go 项目: nise-nabe/NisePostGo

func initTemplate() *template.Template {
	t, parseErr := template.ParseGlob("template/*.tmpl")
	if parseErr != nil {
		log.Panicln("NisePostGo: ", parseErr)
	}
	return t
}

示例#16
文件: goingup.go 项目: WhoBrokeTheBuild/goingup

// Run finalizes all options and calls the ListenAndServe function to serve
// requests
func (a *App) Run() {
	fmt.Println("GoingUp App Starting")

	r := mux.NewRouter()

	fs := http.FileServer(http.Dir(a.Options.StaticAssetsDir))
	r.PathPrefix(a.Options.StaticAssetsURL).Handler(http.StripPrefix(a.Options.StaticAssetsURL, fs))

	fmt.Println("Parsing Templates")
	a.Templates = template.Must(template.ParseGlob(a.Options.TemplateDir + "/*"))

	fmt.Println("Parsing Content")
	a.Content = parseContentGlob(a.Options.ContentDir + "/*.md")

	for _, page := range a.Pages {
		content := ""
		if page.ContentName != "" {
			if val, exists := a.Content[page.ContentName]; exists {
				content = val
			}
		}
		page.Content = template.HTML(content)
		r.HandleFunc(page.URL, makePageHandler(a, page))
	}

	strPort := strconv.Itoa(a.Options.Port)
	fmt.Printf("Listening on %s\n", strPort)
	http.ListenAndServe(":"+strPort, newLogHandler(r))
}

示例#17
文件: app.go 项目: jondavidcody1/rtgo

func (a *App) Parse(filepath string) {
	var (
		hashkey  []byte
		blockkey []byte
	)
	file, err := ioutil.ReadFile(filepath)
	if err != nil {
		log.Fatal("Could not parse config.json: ", err)
	}
	if err := json.Unmarshal(file, a); err != nil {
		log.Fatal("Error parsing config.json: ", err)
	}
	if a.Hashkey == "" {
		hashkey = securecookie.GenerateRandomKey(16)
	} else {
		hashkey = []byte(a.Hashkey)
	}
	if a.Blockkey == "" {
		blockkey = securecookie.GenerateRandomKey(16)
	} else {
		blockkey = []byte(a.Blockkey)
	}
	a.Scook = securecookie.New(hashkey, blockkey)
	a.Templates = template.Must(template.ParseGlob("./static/views/*"))
}

示例#18
文件: mime_html.go 项目: jmptrader/go-rest

// NewHTML create a HTMLMarshaller with path to templates.
func NewHTML(path string) (Marshaller, error) {
	t, err := template.ParseGlob(path + "/*")
	if err != nil {
		return nil, err
	}
	return &HTMLMarshaller{t}, err
}

示例#19
文件: tasks.go 项目: ryanttb/encore

func NewTaskServer(s store.Store, serverUrl, templatesPath, geoipDatabase string) *measurementsServerState {
	queries := make(chan *store.Query)
	go s.WriteQueries(queries)

	measurementIds := generateMeasurementIds()

	go s.ScheduleTaskFunctions()

	taskRequests := make(chan *store.TaskRequest)
	go s.Tasks(taskRequests)

	countResultsRequests := make(chan store.CountResultsRequest)
	go s.CountResultsForReferrer(countResultsRequests)

	geolocator, err := geoip.Open(geoipDatabase)
	if err != nil {
		log.Fatalf("error opening geoip database: %v", err)
	}

	return &measurementsServerState{
		Store:                s,
		Templates:            template.Must(template.ParseGlob(filepath.Join(templatesPath, "[a-zA-Z]*"))),
		Queries:              queries,
		MeasurementIds:       measurementIds,
		TaskRequests:         taskRequests,
		CountResultsRequests: countResultsRequests,
		ServerUrl:            serverUrl,
		Geolocator:           geolocator,
	}
}

示例#20
文件: actions.go 项目: DeyV/go-newsagg

func actionCategoryList(w http.ResponseWriter, req *http.Request) {

	Id := req.URL.Query().Get("id")
	fmt.Println(Id)

	// // param := req.Vars()
	// catId, ok := param["id"]
	// if ok == nil {
	// 	catId = 0
	// }

	var templActionHome *template.Template = template.Must(
		template.ParseGlob("templates/home/*.html"))

	lay := getLayoutTemplates()
	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": getEntryList("", 10),
		"Test": "Test",
	}

	err := templActionHome.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay.New("title").Parse("Najnowsze wpisy - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}

示例#21
文件: main.go 项目: RaviTezu/GolangTraining

func main() {
	tpl, _ = template.ParseGlob("templates/html/*.html")
	http.HandleFunc("/", home)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public/"))))
	http.ListenAndServe(":8080", nil)
}

示例#22
文件: actions.go 项目: DeyV/go-newsagg

func actionCategories(w http.ResponseWriter, req *http.Request) {
	var templActionCategories *template.Template = template.Must(
		template.ParseGlob("templates/categories/*.html"))

	wr := &HtmlContainer{}

	// templActionHome.Funcs(template.FuncMap{"len": Len})
	data := HtmlAssigner{
		"List": category.GetTagCloud(),
		"Test": "Test",
	}

	err := templActionCategories.Execute(wr, data)
	if err != nil {
		fmt.Errorf("%v", err)
	}

	lay := getLayoutTemplates()
	lay.New("title").Parse("Lista Kategorii - " + config.GetStringDef("page", "title", ""))

	err = lay.Execute(w, wr.getHtml())
	if err != nil {
		fmt.Errorf("%v", err)
	}
}

示例#23
文件: main.go 项目: ph3ng/CSCI-130-Spring-16

func init() {
	http.HandleFunc("/", handler)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css/"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img/"))))
	tpl = template.Must(template.ParseGlob("*.html"))
}

示例#24
文件: step5.go 项目: yash0690/Golang

func init() {
	var err error
	myTemplates, err = template.ParseGlob("*.gohtml")
	if err != nil {
		log.Println(err)
	}
}

示例#25
文件: freegeoip.go 项目: hatahet/freegeoip

func main() {
	cf := flag.String("config", "freegeoip.conf", "set config file")
	flag.Parse()
	if buf, err := ioutil.ReadFile(*cf); err != nil {
		log.Fatal(err)
	} else {
		conf = &Settings{}
		if err := xml.Unmarshal(buf, conf); err != nil {
			log.Fatal(err)
		}
	}
	templates = template.Must(template.ParseGlob(fmt.Sprintf("%s/template/*.html", conf.DocumentRoot)))
	http.Handle("/", http.FileServer(http.Dir(conf.DocumentRoot)))
	h := GeoipHandler()
	http.HandleFunc("/csv/", h)
	http.HandleFunc("/xml/", h)
	http.HandleFunc("/json/", h)
	http.HandleFunc("/map/", h)
	server := http.Server{
		Addr: conf.Addr,
		Handler: httpxtra.Handler{
			Logger:   logger,
			XHeaders: conf.XHeaders,
		},
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
	}
	log.Printf("FreeGeoIP server starting on %s (xheaders=%t)",
		conf.Addr, conf.XHeaders)
	if e := httpxtra.ListenAndServe(server); e != nil {
		log.Println(e.Error())
	}
}

示例#26
文件: render.go 项目: konginteractive/cme

func init() {
	// /Users/henrilepic/gocode/src/github.com/konginteractive/cme/
	templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("./app/vues/*"))
	templatesText = textTempl.Must(textTempl.ParseGlob("./app/vues/*"))
	// permet d'avoir quelques variables
	//fmt.Println("YS : " + YS + " / MS : " + MS)
}

示例#27
文件: http.go 项目: SohoStudio/nsq

func httpServer(listener net.Listener) {
	var err error
	templates, err = template.ParseGlob(fmt.Sprintf("%s/*.html", *templateDir))
	if err != nil {
		log.Printf("ERROR: %s", err.Error())
	}

	log.Printf("HTTP: listening on %s", listener.Addr().String())

	handler := http.NewServeMux()
	handler.HandleFunc("/ping", pingHandler)
	handler.HandleFunc("/", indexHandler)
	handler.HandleFunc("/nodes", nodesHandler)
	handler.HandleFunc("/topic/", topicHandler)
	handler.HandleFunc("/delete_topic", deleteTopicHandler)
	handler.HandleFunc("/delete_channel", deleteChannelHandler)
	handler.HandleFunc("/empty_channel", emptyChannelHandler)

	server := &http.Server{
		Handler: handler,
	}
	err = server.Serve(listener)
	// theres no direct way to detect this error because it is not exposed
	if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
		log.Printf("ERROR: http.Serve() - %s", err.Error())
	}

	log.Printf("HTTP: closing %s", listener.Addr().String())
}

示例#28
文件: main.go 项目: mjrmyke/GoLangCourse

func init() {
	//html files, and strips prefixes for img and css
	tpl, _ = template.ParseGlob("*.html")
	http.HandleFunc("/", main)
	http.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("css"))))
	http.Handle("/img/", http.StripPrefix("/img", http.FileServer(http.Dir("img"))))
}

示例#29
文件: groupStatus.go 项目: AnnAddicks/hostq

/* group/status/{groupUUID}
   Respond with the group name, current queue, who is up next in that queue, and if this week has a host yet.
   I'm not sure what this app is going to be yet, api with spa? or server & client code
*/
func DisplayGroupStatus(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	pathVars := mux.Vars(r)

	uuid := pathVars["uuid"]
	ctx.Infof("UUID: %s", uuid)

	if isValidUUID((uuid)) {
		group, err := GetGroupByUUID(ctx, uuid)
		ctx.Infof("group: %v", group)
		if err != nil {
			panic(err)
		}

		status := convertToStatus(group)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")

		var tpl = template.Must(template.ParseGlob("templates/*.html"))
		if err := tpl.ExecuteTemplate(w, "status.html", status); err != nil {
			ctx.Infof("%v", err)
		}

	} else {
		w.Write([]byte("Invalid group"))
	}
}

示例#30
文件: session.go 项目: mehulsbhatt/go-hightech

func loadTemplates() {
	if Templates == nil {
		t, _ := template.ParseGlob(
			filepath.Join(config.Get("email"), "*.*"))
		Templates = t
	}
}

展开阅读全文