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)) }
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) }
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") }
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 }
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()) } } }
/* * 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 }
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"), )) }
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 }
// 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) }
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 }
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!") } }
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()) }
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 }
// 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"))), } }
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 }
func AddBookHandler(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 } user := cookie.Value locals := make(map[string]interface{}) locals["booklist"] = dao.QueryBooksByUserName(user) if r.Method == "GET" { tmpl, _ := template.ParseFiles("./static/addbook.html") locals["user"] = user tmpl.Execute(w, locals) return } if r.Method == "POST" { user := r.FormValue("user") fmt.Println(user) bookName := r.FormValue("book") fmt.Println(bookName) if user == "" || bookName == "" { fmt.Println("valid error!") msg := "error,please input book name and username" tmpl, _ := template.ParseFiles("./static/error.html") tmpl.Execute(w, msg) return } fmt.Println("valid ok") author := r.FormValue("author") describe := r.FormValue("describe") book := new(dao.Book) book.UserName = user book.Name = bookName book.Author = author book.Describe = describe fmt.Println(book) dao.CreateBook(book) userInfo := dao.QueryUserByUserName(user) dao.IncreaseUserBookInfoCount(1, userInfo.Id, 0) //count+1 , 0 means own_book_cout locals["book"] = book locals["user"] = user locals["msg"] = " 图书创建成功" tmpl, _ := template.ParseFiles("./static/addbook.html") tmpl.Execute(w, locals) } }
func ReloadTemplates(resourcesDir string) { addTaskTemplate = template.Must(template.ParseFiles( filepath.Join(resourcesDir, "templates/chromium_perf.html"), filepath.Join(resourcesDir, "templates/header.html"), filepath.Join(resourcesDir, "templates/titlebar.html"), )) runsHistoryTemplate = template.Must(template.ParseFiles( filepath.Join(resourcesDir, "templates/chromium_perf_runs_history.html"), filepath.Join(resourcesDir, "templates/header.html"), filepath.Join(resourcesDir, "templates/titlebar.html"), )) }
func ReloadTemplates(resourcesDir string) { runsHistoryTemplate = template.Must(template.ParseFiles( filepath.Join(resourcesDir, "templates/runs_history.html"), filepath.Join(resourcesDir, "templates/header.html"), filepath.Join(resourcesDir, "templates/titlebar.html"), )) pendingTasksTemplate = template.Must(template.ParseFiles( filepath.Join(resourcesDir, "templates/pending_tasks.html"), filepath.Join(resourcesDir, "templates/header.html"), filepath.Join(resourcesDir, "templates/titlebar.html"), )) }
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") // // blogTmpl, err = template.ParseFiles(templateDir + "/article.htm") // // if err != nil { // // fmt.Println(err) // // } // // blogTmpl = blogTmpl.Funcs(plus) blogTmpl = template.Must(new(template.Template).Funcs(plus).ParseFiles(templateDir + "/article.htm")) }
func (t *Template) Render(w io.Writer) { var tpl *template.Template if !t.DisableLayout { tpl, _ = template.ParseFiles("views/"+t.Layout, "views/"+t.RequestTemplate) } else { tpl, _ = template.ParseFiles("views/" + t.RequestTemplate) } tpl.Execute(w, t.Data) }
func templateInit() { if templates == nil { templates = make(map[string]*template.Template) } templates["view"] = template.Must(template.ParseFiles( "templates/base.html", "templates/view.html")) templates["edit"] = template.Must(template.ParseFiles( "templates/base.html", "templates/edit.html")) templates["d3"] = template.Must(template.ParseFiles( "templates/d3base.html", "templates/ddd.html")) }
func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //get request method if r.Method == "GET" { t, _ := template.ParseFiles("static/index.html") t.Execute(w, nil) } else { r.ParseForm() // logic part of log in fmt.Println("username:"******"usermail"]) fmt.Println("password:"******"passwd"]) t, _ := template.ParseFiles("static/index.html") t.Execute(w, nil) } }
// List all the WaterTests. func watertestListHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("method waterTestListHandler:", r.Method) // get request method if r.Method == "GET" { // Init waterTestData := &WaterTestData{} // Get data form DB err := Vault.Mongo.C("WaterTestResults").Find(bson.M{}).Sort("-Created").All(&waterTestData.WaterTests) CheckError(err) fmt.Println("Number of WaterTests: ", len(waterTestData.WaterTests)) // Get the path to the PlotModel for index, element := range waterTestData.WaterTests { waterTestData.WaterTests[index].PlotReport = getWaterTestPlotModelPath(element.PlotReport, element.SerialNumber) } // Display data to page t, _ := template.ParseFiles("header.html", "watertest_list.html", "footer.html") t.ExecuteTemplate(w, "header", nil) t.ExecuteTemplate(w, "content", waterTestData) t.ExecuteTemplate(w, "footer", nil) t.Execute(w, waterTestData) } else { // Init waterTestData := &WaterTestData{} // Get the partial serial number formData, err := forms.Parse(r) CheckError(err) var partialSerial = formData.Get("PartialSerialNumber") waterTestData.WaterTests = *getWaterTestContain(partialSerial) fmt.Println("Number of WaterTests: ", len(waterTestData.WaterTests)) // Get the path to the PlotModel for index, element := range waterTestData.WaterTests { waterTestData.WaterTests[index].PlotReport = getWaterTestPlotModelPath(element.PlotReport, element.SerialNumber) } // Display data to page t, _ := template.ParseFiles("header.html", "watertest_list.html", "footer.html") t.ExecuteTemplate(w, "header", nil) t.ExecuteTemplate(w, "content", waterTestData) t.ExecuteTemplate(w, "footer", nil) t.Execute(w, waterTestData) } }
func init() { var err error loginTPL, err = template.ParseFiles("templates/login.html") if err != nil { log.Println("init loginTPL err ") log.Println(err) } mainTPL, err = template.ParseFiles( "templates/common/header.html", "templates/main.html", "templates/blog/article.html", "templates/blog/articles.html", "templates/common/sidebar.html", "templates/common/footer.html") if err != nil { log.Println("init mainTPL err ") log.Println(err) } adminTPL, err = template.ParseFiles( "templates/common/header.html", "templates/main.html", "templates/blog/article.html", "templates/admin/articles.html", "templates/common/sidebar.html", "templates/common/footer.html") if err != nil { log.Println("init adminTPL err ") log.Println(err) } editTPL, err = template.ParseFiles("templates/blog/edit_article.html") if err != nil { log.Println("init editTPL err ") log.Println(err) } rssTPL, err = template.ParseFiles("templates/rss.xml") if err != nil { log.Println("init rssTPL err ") log.Println(err) } if err == nil { log.Println("init templates ok ") } }
func schedules(w http.ResponseWriter, r *http.Request) { minUnits, err := strconv.Atoi(r.FormValue("minUnits")) if err != nil { minUnits = 0 } maxUnits, err := strconv.Atoi(r.FormValue("maxUnits")) if err != nil { maxUnits = math.MaxInt32 } schedules, err := generateSchedulesJSON([]byte(r.FormValue("classes")), minUnits, maxUnits) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t, err := texttemplate.ParseFiles("schedules.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } t.Execute(w, schedules) }
func (app *GoApp) homeHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles("home.html") if err != nil { fmt.Fprintf(w, "Under construction.") return } var hTemp HomeTemp session, _ := app.store.Get(r, sessionName) if _, ok := session.Values["user_id"]; ok { hTemp = HomeTemp{ UserName: session.Values["screen_name"].(string), ButtonVal: "Logout", ButtonURL: "/logout", } } else { hTemp = HomeTemp{ UserName: "******", ButtonVal: "Login", ButtonURL: "/login", } } if err := t.Execute(w, hTemp); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) fmt.Println(err) } }
func foo(res http.ResponseWriter, req *http.Request) { templ, error := template.ParseFiles("tpl.gohtml") // Parse template file if error != nil { log.Fatalln(error) } error = templ.Execute(os.Stdout, nil) if error != nil { log.Fatalln(error) } cookie, err := req.Cookie("session-fino") if err != nil { // id, _ := uuid.NewV4() cookie = &http.Cookie{ Name: "session-fino", Value: "0", // Secure: true, HttpOnly: true, } } count, _ := strconv.Atoi(cookie.Value) count++ cookie.Value = strconv.Itoa(count) fmt.Println(cookie) http.SetCookie(res, cookie) templ.ExecuteTemplate(res, "tpl.gohtml", cookie) }
func serveHome() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != "/" { http.Error(w, "Not found", 404) return } if *template_file != "" { if _, err := os.Stat(*template_file); os.IsNotExist(err) { panic("Custom template file not found") } homeTempl = template.Must(template.ParseFiles(*template_file)) } else { bytes, err := Asset("data/templates/home.html") if err != nil { panic(err) } homeTempl = template.Must(template.New("home").Parse(string(bytes))) } w.Header().Set("Content-Type", "text/html; charset=utf-8") homeTempl.Execute(w, template_vars) }) }
func Index(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles(filepath.Join("templates", "index.gohtml")) if err != nil { log.Fatal(err) } ctx := duktape.New() err = loadJSFiles(ctx, "static/duktape-polyfill.js", "static/react.js", "static/react-dom-server.js", "static/components.js", "static/server.js", ) if err != nil { log.Fatal(err) } component, err := renderServer(ctx, "Claudemiro") if err != nil { log.Fatal(err) } t.Execute(w, component) }
// write writes the configuration file, will write to stdout if dryRun == true func (cfg *loadBalancerConfig) write(services map[string][]service, dryRun bool) (err error) { var w io.Writer if dryRun { w = os.Stdout } else { w, err = os.Create(cfg.Config) if err != nil { return } } var t *template.Template t, err = template.ParseFiles(cfg.Template) if err != nil { return } conf := make(map[string]interface{}) conf["startSyslog"] = strconv.FormatBool(cfg.startSyslog) conf["services"] = services // default load balancer algorithm is roundrobin conf["defLbAlgorithm"] = lbDefAlgorithm if cfg.lbDefAlgorithm != "" { conf["defLbAlgorithm"] = cfg.lbDefAlgorithm } err = t.Execute(w, conf) return }