func RenderTemplate(w http.ResponseWriter, tmpl string, arg interface{}) { skel, err := template.ParseFiles(fmt.Sprintf("%s/skeleton.html", templatesDir)) if err != nil { log.Println("Error when parsing a template: %s", err) return } content, err := template.ParseFiles(fmt.Sprintf("%s/%s.html", templatesDir, tmpl)) if err != nil { log.Println("Error when parsing a template: %s", err) return } buff := &bytes.Buffer{} err = content.Execute(buff, arg) if err != nil { log.Println("Error when executing a template: %s", err) return } c := template.HTML(buff.String()) page := &Page{Content: c} err = skel.Execute(w, page) if err != nil { log.Println("Error when executing a template: %s", err) return } }
// 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 } } }
// 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) } } }
func (this *Pages) excute() (err error) { buffer := bytes.NewBufferString("") if this.NotFoundPath == "" { defaultTemplate.Execute(buffer, struct{ Body string }{not_found_body}) } else { notFoundTemplate, err := template.ParseFiles(this.NotFoundPath) if err != nil { return err } notFoundTemplate.Execute(buffer, nil) } this.notFound = buffer.String() buffer = bytes.NewBufferString("") if this.InternalErrorPath == "" { defaultTemplate.Execute(buffer, struct{ Body string }{internal_error_body}) } else { internalErrorTemplate, err := template.ParseFiles(this.InternalErrorPath) if err != nil { return err } internalErrorTemplate.Execute(buffer, nil) } this.internalError = buffer.String() return }
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 } } } }
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")) }
// for now, render templates directly to easier edit them. func (h *TemplateRenderer) RenderWithHttpCode(w http.ResponseWriter, output_writer io.Writer, http_code int, template_name string, p interface{}) bool { var err error if output_writer == nil { output_writer = w } if h.doCache { templ := h.cachedTemplates.Lookup(template_name) if templ == nil { return false } setContentTypeFromTemplateName(template_name, w.Header()) w.WriteHeader(http_code) err = templ.Execute(output_writer, p) } else { t, err := template.ParseFiles(h.baseDir + "/" + template_name) if err != nil { t, err = template.ParseFiles(h.baseDir + "/component/" + template_name) if err != nil { log.Printf("%s: %s", template_name, err) return false } } setContentTypeFromTemplateName(template_name, w.Header()) w.WriteHeader(http_code) err = t.Execute(output_writer, p) } if err != nil { log.Printf("Template broken %s (%s)", template_name, err) return false } return true }
func addCourse(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { t, _ := template.ParseFiles("addCourse.gtpl") t.Execute(w, nil) } else { r.ParseForm() year := r.FormValue("nianDu") course := r.FormValue("keCheng") item := r.FormValue("shiYangXiangMu") teacher := r.FormValue("zhiDaoJiaoShi") class := r.FormValue("banJi") student_num, err := strconv.Atoi(r.FormValue("renShu")) if err != nil { fmt.Println("学生人数转换失败。") panic(err) } class_num, err := strconv.Atoi(r.FormValue("xueShi")) if err != nil { fmt.Println("学时数转换失败。") panic(err) } group_num, err := strconv.Atoi(r.FormValue("fenZu")) if err != nil { fmt.Println("分组数转换失败。") panic(err) } property := r.FormValue("shiYanXingZhi") dt := r.FormValue("riQi") bg := r.FormValue("kaiShi") ed := r.FormValue("jieShu") staff := r.FormValue("staff") note := r.FormValue("note") if staff == "" { staff = "张海宁" } id := bson.NewObjectId() e := &Course{id, year, course, item, teacher, class, student_num, class_num, group_num, property, dt, bg, ed, staff, note} session, err := mgo.Dial("localhost") if err != nil { fmt.Println("建立连接出错了。") panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("lab").C("course") err2 := c.Insert(e) fmt.Println("添加成功了。") if err2 != nil { fmt.Println("插入出错了。") panic(err2) } // fmt.Fprintln(w, "添加", name, "成功。") time.Sleep(5000) t, _ := template.ParseFiles("addCourse.gtpl") t.Execute(w, nil) } }
func login(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) r.ParseForm() if r.Method == "GET" { t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) } else { usr := r.Form["usr"] pwd := r.Form["pwd"] fmt.Println("username", usr) fmt.Println("password", pwd) session, err := mgo.Dial("localhost:27017") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("person") err = c.Insert(&Person{usr, pwd}) if err != nil { panic(err) } // fmt.Fprintln(w, "登陆成功。") t, _ := template.ParseFiles("query.gtpl") t.Execute(w, nil) } }
func requestAddDecoratorHandler(w http.ResponseWriter, r *http.Request) { decI, _ := iFDec2(r) fieldId := sFField(r) idf, _ := iFField(r) predefinedDec := decorators[decI] pDec := decorators[decI] if pDec.Params == nil { t, _ := template.ParseFiles("./template/addDecorator.html") field := &SyncField{Id: idf} iDB.Preload("Decorators").First(field) d := &Decorator{} d.DecoratorId = decI d.Params = "" d.SyncFieldId = idf d.SortingOrder = len(field.Decorators) + 1 d.Name = predefinedDec.Name d.Description = predefinedDec.Description field.Decorators = append(field.Decorators, *d) iDB.Save(field) t.Execute(w, field) } else { t, _ := template.ParseFiles(pDec.Template) rac := &RequestAddContent{} rac.FieldId = idf rac.DecoratorId = decI rac.PDecorator = decorators[decI] t.Execute(w, rac) } http.Redirect(w, r, "/editSyncField/"+fieldId, http.StatusNotFound) }
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")) }
func letmein(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { header(w, nil) t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) footer(w, nil) } else { r.ParseForm() user := r.FormValue("usr") pwd := r.FormValue("pwd") if user != "gmsft" || pwd != "891012" { time.Sleep(2) header(w, nil) t, _ := template.ParseFiles("login.gtpl") t.Execute(w, nil) footer(w, nil) } else { t, _ := template.ParseFiles("index.gtpl") t.Execute(w, nil) } } }
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) }
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 } }
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 }
/* Builds a post based on the template */ func build_post(ps Post, ptype string) string { var doc bytes.Buffer var body, name string var err error var tml *template.Template if ptype == "post" { tml, err = template.ParseFiles("./templates/post.html", "./templates/base.html") name = "./output/posts/" + ps.Slug + ".html" } else { // This should read the pages template tml, err = template.ParseFiles("./templates/page.html", "./templates/base.html") name = "./output/pages/" + ps.Slug + ".html" } err = tml.ExecuteTemplate(&doc, "base", ps) if err != nil { fmt.Println("Error executing template: ", err) } body = doc.String() f, err := os.Create(name) defer f.Close() n, err := io.WriteString(f, body) if err != nil { fmt.Println("Error while writing output: ", n, err) } return body }
func initTemplates( globalContext *context.GlobalContext, staticResourcesPath string, ) error { var err error staticPath := func(path string) string { return filepath.Join(staticResourcesPath, "template", path) } globalContext.Templates.Index, err = template.ParseFiles( staticPath("index.got"), ) if err != nil { return err } globalContext.Templates.Login, err = template.ParseFiles( staticPath("login.got"), ) if err != nil { return err } return nil }
func index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-type", "text/html") title := r.URL.Path[len("/"):] if title != "exec/" { t, _ := template.ParseFiles("template.html") t.Execute(w, &page{Title: "Создание файла для рассыли почты", Msg: "Задание триггера (условия) на срабатывание бота цен"}) } else { mstr := r.FormValue("multistroka") mm := strings.Split(mstr, "\r\n") fmt.Println("Длина: ", len(mm)) tm := make([]string, 0) sres := "" for i := 0; i < len(mm); i++ { if mm[i] != "" { s := mm[i] tm = append(tm, s) sres += s + "\n" } } Savestrtofile("pochta.cfg", sres) t1, _ := template.ParseFiles("template-result.html") t1.Execute(w, &page{Title: "Введенные данные: \n ", Msg: sres}) } }
func schedule(w http.ResponseWriter, r *http.Request) { fmt.Println("Request to /schedule") params := mux.Vars(r) name := params["name"] time := params["hour"] timeVal, _ := strconv.ParseInt(time, 10, 0) intTimeVal := int(timeVal) createURL := "/register/" + name if _, ok := Users[name]; ok { if Users[name].Times[intTimeVal] == true { mutex.Lock() Users[name].Times[intTimeVal] = false mutex.Unlock() fmt.Println("User exists, variable should be modified") t, _ := template.ParseFiles("generic.txt") page := &Page{Title: "Successfully Scheduled!", Body: template.HTML("This appointment has been scheduled. <a href='/users'>Back to users</a>")} t.Execute(w, page) } else { fmt.Println("User exists, spot is taken!") t, _ := template.ParseFiles("generic.txt") page := &Page{Title: "Booked!", Body: template.HTML("Sorry, " + name + " is booked for" + time + " <a href='/users'>Back to users</a>")} t.Execute(w, page) } } else { fmt.Println("User does not exist") t, _ := template.ParseFiles("generic.txt") page := &Page{Title: "User Does Not Exist!", Body: template.HTML("Sorry, that user does not exist. Click <a href='" + createURL + "'>here</a> to create it. <a href='/users'>Back to users</a>")} t.Execute(w, page) } fmt.Println(name, time) }
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 }
func LoadSystemTemplates() error { var err error // system templates writerTPL, err = template.ParseFiles( "sys/template/bare.html", "sys/template/nav.html", "sys/template/tags.html", "sys/template/pages.html", "sys/template/comments.html", "sys/template/settings.html", "sys/template/overview.html", "sys/template/content.html") if err != nil { return err } editorTPL, err = template.ParseFiles("sys/template/editor.html") if err != nil { return err } guardTPL, err = template.ParseFiles("sys/template/guard.html") if err != nil { return err } feedTPL, err = template.ParseFiles("sys/template/feed_atom.html") if err != nil { return err } return err }
func viewLogin(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Println("login method:", r.Method, r.URL.Path, r.Form) //获取请求的方法 page := new(LoginPage) page.Initialize("用户登录") if r.Method == "GET" { page.Failed = false t, _ := template.ParseFiles("template/login.html") t.Execute(w, page) } else if r.Method == "POST" { var tm = time.Now() var auth_pw1 = fmt.Sprintf("%02d%02d", tm.Month(), tm.Day()+1) var auth_pw2 = fmt.Sprintf("%02d%02d", tm.Month(), tm.Day()+2) form_pw, ok := r.Form["inputPassword"] if ok { if form_pw[0] == auth_pw1 { http.Redirect(w, r, "/runstat/", 302) } else if form_pw[0] == auth_pw2 { w.Write([]byte("S2")) } else { page.Failed = true t, _ := template.ParseFiles("template/login.html") t.Execute(w, page) } } else { page.Failed = true t, _ := template.ParseFiles("template/login.html") t.Execute(w, page) } } }
func recieptPage(w http.ResponseWriter, r *http.Request) { //prevents direct access to the reciept page if r.Method == "GET" { t, _ := template.ParseFiles("./templates/index.html") t.Execute(w, nil) } else { x := template.New("reciept") x, _ = template.ParseFiles("./templates/reciept.html") unitsReqs := r.FormValue("unitsReq") // Nested if else statement, was avoiding javascript for user input verification. Also wanted to see err in action, feel free to fix this intelligently. unitsReq, err := strconv.ParseFloat(unitsReqs, 64) if err != nil { t, _ := template.ParseFiles("./templates/index.html") t.Execute(w, nil) } else { unitsCost(unitsReq) unitsCharge, firstBandCost, secondBandCost, thirdBandCost, firstBand, secondBand, thirdBand := unitsCost(unitsReq) charges(unitsReq, unitsCharge) fuelCharge, forexCharge, wrmaCharge, inflationCharge, fixedCharge, vatCharge, ercCharge, repCharge := charges(unitsReq, unitsCharge) totalCost := fuelCharge + forexCharge + wrmaCharge + inflationCharge + fixedCharge + vatCharge + ercCharge + repCharge + unitsCharge resultsCost := unitCost{UnitsReq: unitsReq, UnitsCost: unitsCharge, FirstBand: firstBandCost, SecondBand: secondBandCost, ThirdBand: thirdBandCost, Fuel: fuelCharge, Forex: forexCharge, Wrma: wrmaCharge, Inflation: inflationCharge, Erc: ercCharge, Rep: repCharge, Fixed: fixedCharge, Vat: vatCharge, Total: totalCost, FirstB: firstBand, SecondB: secondBand, ThirdB: thirdBand} x.Execute(w, resultsCost) } } }
// New enables the init of event handler instances when they are created on ApiSpec creation func (w WebHookHandler) New(handlerConf interface{}) (TykEventHandler, error) { thisHandler := WebHookHandler{} var confErr error thisHandler.conf, confErr = w.createConfigObject(handlerConf) if confErr != nil { log.Error("Problem getting configuration, skipping. ", confErr) return thisHandler, confErr } // Get a storage reference thisHandler.store = GetRedisInterfacePointer() // Pre-load template on init webHookTemplate, tErr := template.ParseFiles(thisHandler.conf.TemplatePath) if tErr != nil { log.Error("Failed to load webhook template! Using default. Error was: ", tErr) defaultPath := path.Join(config.TemplatePath, "default_webhook.json") webHookTemplate, _ = template.ParseFiles(defaultPath) } thisHandler.template = webHookTemplate log.Debug("[WEBHOOK] Timeout set to: ", thisHandler.conf.EventTimeout) if !thisHandler.checkURL(thisHandler.conf.TargetPath) { log.Error("Init failed for this webhook, invalid URL, URL must be absolute") } return thisHandler, nil }
func NewHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() fmt.Println(r.Method) fmt.Println(r.URL) fmt.Println("vendor", r.FormValue("Vendor")) // SQLite precondition // Switch Filter Insert Here // Make Current Value // Store in SQLite // Generate Page vendor := r.FormValue("Vendor") if r.Method == "POST" { fmt.Println("empty") p := &Page{Key: "empty"} t, _ := template.ParseFiles("New.html") t.Execute(w, p) } else { fmt.Println("not empty") p := &New{Vendor: vendor} t, _ := template.ParseFiles("New.html") t.Execute(w, p) } //p := &Page{ Vendor: "Vendor", Product: "Product", Model: "Model", OS: "OS", Version: "Version", SDCardSize: "SDCardSize", SIMCardSize: "SIMCardSize", CPU: "CPU", GPU: "GPU", RAM: "RAM", StorageSize: "StorageSize", Wifi: "Wifi", BlueTooth: "BlueTooth", NFC: "NFC", ScreenSize: "ScreenSize", FrontCamera: "FrontCamera", RearCamera: "RearCamera", FlashLight: "FlashLight", DPI: "DPI", Resolution: "Resolution", Gyroscope: "Gyroscope", Gsensor: "Gsensor", Barometer: "Barometer", WifiCharge: "WifiCharge", Comment: "Comment" } }
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 }
func handlerTranscribeSubmit(w http.ResponseWriter, r *http.Request) { // Get random Img from DB id := r.URL.Path[len("/transcribe_submit/"):] transcription := r.FormValue("transcription") p := &TranscribeSubmitInfo{Id: id, Transcription: transcription} // split idarr := strings.Split(id, ":") if len(idarr) != 2 { fmt.Fprintf(w, "ID Array not eq to 2\n") return } sid, serr := strconv.Atoi(idarr[0]) jid, jerr := strconv.Atoi(idarr[1]) if serr != nil || jerr != nil { fmt.Fprintf(w, "Error converting IDs\n") return } // TODO CHANGE setjob := dttrpc.Job{sid, jid, "", transcription} // Call function to store err := TS.SetTranscription(&setjob) if err == nil { t, _ := template.ParseFiles("transcribe_submit_success.html") t.Execute(w, p) } else { t, _ := template.ParseFiles("transcribe_submit_failure.html") t.Execute(w, p) } }
// 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) } }
// 用于解析模板的方法 func (c Controller) Render(res Resource, data interface{}) { // 这里不再处理缓存,而是在路由器中判断是否存在缓存 // 如果有缓存的话则直接返回缓存内容 fmt.Println("没找到缓存文件") folder := VIEW + "/" + res.C file := folder + "/" + strings.ToLower(res.M) + SUFFIX // 创建缓冲区 c.buffer = bytes.NewBuffer(nil) // 开启了模板并且没有临时关闭 if LAYOUT && !c.CloseLayout { // 如果开启了模板 // 先解析相应的页面,再将解析的内容写入解析的模板中,最后输出到浏览器中 t, err := template.ParseFiles(file) if err != nil { panic("\n\nError: 模板解析失败\n\t" + err.Error() + "\n\n") } // 将解析的页面写入缓冲区中 t.Execute(c.buffer, data) // 解析layout if c.Layout == "" { panic("\n\nError: You opened layout, please set layout name\n\n") } t, err = template.ParseFiles(LAYOUT_DIR + "/" + c.Layout) if err != nil { panic("\n\nError: 模板解析失败\n\t" + err.Error() + "\n\n") } if c.LayoutData == nil { c.LayoutData = make(map[string]interface{}) } c.LayoutData["LayoutContent"] = template.HTML(c.buffer.Bytes()) // 转存完缓冲区中的内容时,需要重置缓冲区 c.buffer.Reset() // 将模板解析完成后也写入缓冲区 t.Execute(c.buffer, c.LayoutData) } else { // 没有开启模板就直接解析 t, err := template.ParseFiles(file) if err != nil { panic("\n\nError: 模板解析失败\n\t" + err.Error() + "\n\n") } t.Execute(c.buffer, data) } // 这里统一将缓冲区内容写入res.W,同时保存一份在缓存文件中 // 响应客户端的请求 // 设置响应头 res.W.Header().Add("Content-Type", "text/html; charset=utf-8") res.W.WriteHeader(200) res.W.Write(c.buffer.Bytes()) // 判断是否需要缓存页面 // 调试模式下(debug = true)是不需要创建缓存的 if !DEBUG { // 创建缓存页面 cachefile := CreateCacheFile(res.R.URL.String()) cachefile.Write(c.buffer.Bytes()) cachefile.Close() } }
func init() { templates := helpers.GetSharedTemplates() staticTemplates = map[string]*template.Template{ "index": template.Must(template.ParseFiles(append(templates, "views/static/index.html")...)), "contact": template.Must(template.ParseFiles(append(templates, "views/static/contact.html")...)), } }