本文整理汇总了Golang中text/template.ParseFiles函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseFiles函数的具体用法?Golang ParseFiles怎么用?Golang ParseFiles使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseFiles函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
HOME := os.Getenv("HOME")
if HOME == "" {
HOME = "/root"
}
var listenPort string
flag.StringVar(&listenPort, "listen", "8080", "Port to listen on")
flag.StringVar(&basePath, "root", HOME, "Base path to serve files from '/'")
flag.Parse()
_, err := os.Open(basePath)
if err != nil {
panic(err)
}
templateDirListing, _ = template.ParseFiles("dir_listing.html.got")
templateNotFound, _ = template.ParseFiles("404.html.got")
log.Println("Listening on port", listenPort)
http.HandleFunc("/", handler)
// for some reason can't get http.FileServer to work properly
// this probably isn't the best way to do this - if you have a folder called 'static'
// in basePath then the static handler will take precedence
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "."+r.URL.Path)
})
panic(http.ListenAndServe(":"+listenPort, nil))
}
示例2: RegisterHandler
func RegisterHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
tmpl, _ := template.ParseFiles("./static/adduser.html")
tmpl.Execute(w, "")
return
}
username := r.FormValue("user")
pwd := r.FormValue("pwd")
pwdConfirm := r.FormValue("pwd_confirm")
user := dao.QueryUserByUserName(username)
if user != nil {
io.WriteString(w, "user "+username+"alread exists")
return
}
if pwd == "" || pwd != pwdConfirm {
io.WriteString(w, "password confirm error, not the same one!")
return
}
user = new(dao.User)
user.UserName = username
user.Name = username
user.Pwd = wb_util.CreateMD5String(pwd)
dao.CreateUser(user)
dao.RegistUser(user)
msg := "register success!!!"
tmpl, _ := template.ParseFiles("./static/success.html")
tmpl.Execute(w, msg)
}
示例3: init
func init() {
ThemeDir, _ = osext.ExecutableFolder()
ThemeDir += "/../src/github.com/superhx/goblog/theme"
templateDir = ThemeDir + "/template"
homeTmpl, _ = template.ParseFiles(templateDir + "/home.htm")
blogTmpl, _ = template.ParseFiles(templateDir + "/article.htm")
}
示例4: NewHttpNotifier
func NewHttpNotifier(app *ApplicationContext) (*HttpNotifier, error) {
// Compile the templates
templatePost, err := template.ParseFiles(app.Config.Httpnotifier.TemplatePost)
if err != nil {
log.Criticalf("Cannot parse HTTP notifier POST template: %v", err)
os.Exit(1)
}
templateDelete, err := template.ParseFiles(app.Config.Httpnotifier.TemplateDelete)
if err != nil {
log.Criticalf("Cannot parse HTTP notifier DELETE template: %v", err)
os.Exit(1)
}
// Parse the extra parameters for the templates
extras := make(map[string]string)
for _, extra := range app.Config.Httpnotifier.Extras {
parts := strings.Split(extra, "=")
extras[parts[0]] = parts[1]
}
return &HttpNotifier{
app: app,
templatePost: templatePost,
templateDelete: templateDelete,
extras: extras,
quitChan: make(chan struct{}),
groupIds: make(map[string]map[string]string),
resultsChannel: make(chan *ConsumerGroupStatus),
}, nil
}
示例5: buyHandler
func buyHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
fmt.Printf("Cannot %s /buy\n", r.Method)
fmt.Fprintf(w, "Cannot %s /buy", r.Method)
return
}
variation_id := r.PostFormValue("variation_id")
member_id := r.PostFormValue("member_id")
//fmt.Fprintf(w, "buy:\n")
//fmt.Printf(" variation_id: %s\n", variation_id)
//fmt.Printf(" member_id: %s\n", member_id)
model := db.Buy(variation_id, member_id)
if model.Result == true {
var t = template.Must(template.ParseFiles("template/buy_complete.html"))
if err := t.Execute(w, model); err != nil {
fmt.Println(err.Error())
}
} else {
var t = template.Must(template.ParseFiles("template/buy_soldout.html"))
if err := t.Execute(w, model); err != nil {
fmt.Println(err.Error())
}
}
}
示例6: Render
/*
* Render page
*
* @param pageFilePath (string)
* @param w (http.ResponseWriter)
*
* @return (error)
*/
func (page *Page) Render(pageFilePath string, w http.ResponseWriter) (err error) {
columnFilePath := page.PageSetting.Layout + ".html"
mainFilePath := "main.html"
contentFilePath := pageFilePath + ".html"
sidebarFilePath := "sidebar.html"
var tmpl *template.Template
switch page.PageSetting.ShowSidebar {
case true:
tmpl, err = template.ParseFiles(
LAYOUT_FOLDER+mainFilePath,
LAYOUT_FOLDER+columnFilePath,
LAYOUT_FOLDER+sidebarFilePath,
STATIC_FOLDER+contentFilePath)
case false:
tmpl, err = template.ParseFiles(
LAYOUT_FOLDER+mainFilePath,
LAYOUT_FOLDER+columnFilePath,
STATIC_FOLDER+contentFilePath)
}
if err != nil {
return
}
tmpl.Execute(w, page)
return
}
示例7: reloadTemplates
func reloadTemplates() {
// Change the current working directory to two directories up from this source file so that we
// can read templates and serve static (res/) files.
if *resourcesDir == "" {
_, filename, _, _ := runtime.Caller(0)
*resourcesDir = filepath.Join(filepath.Dir(filename), "../..")
}
commitsTemplate = template.Must(template.ParseFiles(
filepath.Join(*resourcesDir, "templates/commits.html"),
filepath.Join(*resourcesDir, "templates/header.html"),
))
hostsTemplate = template.Must(template.ParseFiles(
filepath.Join(*resourcesDir, "templates/hosts.html"),
filepath.Join(*resourcesDir, "templates/header.html"),
))
infraTemplate = template.Must(template.ParseFiles(
filepath.Join(*resourcesDir, "templates/infra.html"),
filepath.Join(*resourcesDir, "templates/header.html"),
))
buildbotDashTemplate = template.Must(template.ParseFiles(
filepath.Join(*resourcesDir, "templates/buildbot_dash.html"),
filepath.Join(*resourcesDir, "templates/header.html"),
))
}
示例8: generatePathToPage
func generatePathToPage(templateDirPath string, data *Data) (map[string][]byte, error) {
tmpl, err := template.ParseFiles(filepath.Join(templateDirPath, "go.html"))
if err != nil {
return nil, err
}
indexTmpl, err := template.ParseFiles(filepath.Join(templateDirPath, "index.html"))
if err != nil {
return nil, err
}
pathToPage := make(map[string][]byte)
for path, goRedirect := range data.PathToGoRedirect {
page, err := generatePage(tmpl, goRedirect)
if err != nil {
return nil, err
}
pathToPage[path] = page
}
indexPage, err := generatePage(indexTmpl, data)
if err != nil {
return nil, err
}
for _, indexPath := range indexPaths {
pathToPage[indexPath] = indexPage
}
return pathToPage, nil
}
示例9: Render
// Renders a template
func Render(w http.ResponseWriter, r *http.Request, passedTemplate *bytes.Buffer, Statuscode ...int) {
// Add some HTTP Headers
if len(Statuscode) == 1 {
w.WriteHeader(Statuscode[0])
}
c := appengine.NewContext(r)
u := user.Current(c)
headerdata := HeaderData{}
if u != nil {
headerdata.IsLoggedIn = true
headerdata.Username = u.String()
if user.IsAdmin(c) {
headerdata.IsAdmin = true
}
}
// Header
template.Must(template.ParseFiles("templates/header.html")).Execute(w, headerdata)
// Now add the passedTemplate
fmt.Fprintf(w, "%s", string(passedTemplate.Bytes())) // %s = the uninterpreted bytes of the string or slice
// And now we execute the footer
template.Must(template.ParseFiles("templates/footer.html")).Execute(w, nil)
}
示例10: Write
func (c *DirectorConfig) Write() error {
directorTemplatePath, err := c.assetsProvider.FullPath("director.yml")
if err != nil {
return err
}
t := template.Must(template.ParseFiles(directorTemplatePath))
err = c.saveConfig(c.options.Port, c.DirectorConfigPath(), t)
if err != nil {
return err
}
cpiTemplatePath, err := c.assetsProvider.FullPath("cpi.sh")
if err != nil {
return err
}
cpiTemplate := template.Must(template.ParseFiles(cpiTemplatePath))
err = c.saveCPIConfig(c.CPIPath(), cpiTemplate)
if err != nil {
return err
}
for i := 1; i <= c.numWorkers; i++ {
port := c.options.Port + i
err = c.saveConfig(port, c.WorkerConfigPath(i), t)
if err != nil {
return err
}
}
return nil
}
示例11: main
func main() {
flag.Parse()
homeTempl = template.Must(template.ParseFiles(filepath.Join(*assets, "home.html")))
testTempl = template.Must(template.ParseFiles(filepath.Join(*assets, "test.html")))
// rc := lib.Newredisc(*redisaddr, 0)
// err := rc.StartAndGc()
// if err != nil {
// log.Fatalln(err)
// }
db := new(lib.Tips)
err := db.NewTips(conf.Mysql.Connstr)
http.HandleFunc("/", homeHandler)
http.HandleFunc("/test", testHandler)
h := lib.NewHub()
go h.Run()
go h.Productmessage(db)
go h.ProductHotMessage(db)
http.Handle("/ws", lib.WsHandler{H: h})
log.Println("Server is opening")
err = http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatalln("Listen & Serve Error!")
}
}
示例12: serveTemplate
func serveTemplate(res http.ResponseWriter, name string, data interface{}) {
tpl, err := template.ParseFiles("templates/" + name + ".gohtml")
if err != nil {
http.Error(res, err.Error(), 500)
return
}
var buf bytes.Buffer
err = tpl.Execute(&buf, data)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
body := buf.String()
tpl, err = template.ParseFiles("templates/layout.gohtml")
if err != nil {
http.Error(res, err.Error(), 500)
return
}
buf.Reset()
err = tpl.Execute(&buf, map[string]interface{}{
"Body": body,
})
if err != nil {
http.Error(res, err.Error(), 500)
return
}
res.Header().Set("Content-Type", "text/html")
res.Write(buf.Bytes())
}
示例13: BookNoteHandler
func BookNoteHandler(w http.ResponseWriter, r *http.Request) {
cookie, _ := r.Cookie("user")
fmt.Println(cookie)
if cookie.Value == "" {
msg := "error,please login first"
tmpl, _ := template.ParseFiles("./static/error.html")
tmpl.Execute(w, msg)
return
}
infoId := r.FormValue("info_id")
note := r.FormValue("note")
if note == "" || infoId == "" {
msg := "error,please write note first"
tmpl, _ := template.ParseFiles("./static/error.html")
tmpl.Execute(w, msg)
return
}
infoIdInt64, _ := strconv.ParseInt(infoId, 10, 0)
infoIdInt := (int)(infoIdInt64)
dao.SetBorrowInfoNote(infoIdInt, note)
msg := "write note success!"
tmpl, _ := template.ParseFiles("./static/success.html")
tmpl.Execute(w, msg)
return
}
示例14: loadTemplates
// Loads templates from given directory
func loadTemplates(path string) *Templates {
return &Templates{
template.Must(template.ParseFiles(filepath.Join(path, "activate.txt"))),
template.Must(template.ParseFiles(filepath.Join(path, "delete.txt"))),
htmlTemplate.Must(htmlTemplate.ParseFiles(filepath.Join(path, "connected.html"))),
htmlTemplate.Must(htmlTemplate.ParseFiles(filepath.Join(path, "deleted.html"))),
}
}
示例15: initializeAppTmpl
func (t *templateManager) initializeAppTmpl() error {
prefix := func(filename string) string {
return filepath.Join(t.brog.Config.TemplatePath, filename)
}
indexApp, err := template.ParseFiles(
prefix(appTmplName),
prefix(styleTmplName),
prefix(jsTmplName),
prefix(headerTmplName),
prefix(footerTmplName),
)
if err != nil {
return fmt.Errorf("parsing indexApp template, %v", err)
}
index, err := indexApp.ParseFiles(prefix(indexTmplName))
if err != nil {
return fmt.Errorf("parsing index template at '%s', %v", prefix(indexTmplName), err)
}
postApp, err := template.ParseFiles(
prefix(appTmplName),
prefix(styleTmplName),
prefix(jsTmplName),
prefix(headerTmplName),
prefix(footerTmplName),
)
if err != nil {
return fmt.Errorf("parsing postApp template, %v", err)
}
post, err := postApp.ParseFiles(prefix(postTmplName))
if err != nil {
return fmt.Errorf("parsing post template at '%s', %v", prefix(postTmplName), err)
}
langSelectApp, err := template.ParseFiles(
prefix(appTmplName),
prefix(styleTmplName),
prefix(jsTmplName),
prefix(headerTmplName),
prefix(footerTmplName),
)
if err != nil {
return fmt.Errorf("parsing langSelectApp template, %v", err)
}
langSelect, err := langSelectApp.ParseFiles(prefix(langSelectTmplName))
if err != nil {
return fmt.Errorf("parsing langSelect template at '%s', %v", prefix(langSelectTmplName), err)
}
t.mu.Lock()
t.index = index
t.post = post
t.langselect = langSelect
t.mu.Unlock()
return nil
}