func (a *Article) LoadRelated(s *mgo.Session) { fmt.Println("Meta start") if a.Meta == nil { a.Meta = make(map[string]interface{}) } a.Meta["author"] = a.GetAuthor(s).String() a.Meta["markdown"] = template.HTML(string(blackfriday.MarkdownBasic([]byte(a.Body)))) if len(a.Body) > trimLength { a.Meta["teaser"] = template.HTML(string(blackfriday.MarkdownBasic([]byte(a.Body[0:trimLength])))) } else { a.Meta["teaser"] = template.HTML(string(blackfriday.MarkdownBasic([]byte(a.Body[0:len(a.Body)])))) } fmt.Println("Meta:", a.Meta) }
func TestDocument(t *testing.T) { const markdownIn = `This is Markdown. - Item - Item - Item And here are some ordered items. 1. Item 1 1. Item 2 1. Item 3 Cool. ` renderedHtml := blackfriday.MarkdownBasic([]byte(markdownIn)) t.Log(string(renderedHtml)) parsedHtml, err := html.Parse(bytes.NewReader(renderedHtml)) if err != nil { panic(err) } markdownOut := html_to_markdown.Document(parsedHtml) if markdownIn != markdownOut { goon.DumpExpr(markdownIn, markdownOut) t.Fail() } }
func BlogSaveHandler(w http.ResponseWriter, r *http.Request, title string) { body := r.FormValue("body") const layout = "2006-01-02 15:04:05" t := time.Now() information := t.Format(layout) dBody := template.HTML(blackfriday.MarkdownBasic([]byte(html.EscapeString(body)))) p := &Page{Title: title, DisplayBody: dBody, Information: information} versions := make(map[string]*Page) filename := "./blogs/" + p.Title file, err := os.Open(filename) if err == nil { defer file.Close() decoder := json.NewDecoder(file) decoder.Decode(&versions) } versions[t.Format(layout)] = p out, err := json.Marshal(versions) if err != nil { } ioutil.WriteFile(filename, out, 0600) http.Redirect(w, r, "/blog/"+title, http.StatusFound) }
func SaveHandler(w http.ResponseWriter, r *http.Request, title string) { body := r.FormValue("body") dBody := template.HTML(blackfriday.MarkdownBasic([]byte(html.EscapeString(body)))) const layout = "2006-01-02 15:04:05" t := time.Now() cookie, err := r.Cookie("User") if err != nil { // just do something } author := cookie.Value information := "Aktualisiert:" + t.Format(layout) + " by " + string(author) p := &Page{Title: title, Body: body, DisplayBody: dBody, Information: information} versions := make(map[string]*Page) filename := "./articles/" + p.Title file, err := os.Open(filename) if err == nil { defer file.Close() decoder := json.NewDecoder(file) decoder.Decode(&versions) } versions[t.Format(layout)] = p out, err := json.Marshal(versions) if err != nil { fmt.Println("nicht jsoned") } ioutil.WriteFile(filename, out, 0600) http.Redirect(w, r, "/view/"+title, http.StatusFound) }
func main() { setup() input := readInput(goopt.Args) if input == nil { fmt.Println("No input found") os.Exit(1) } outfile := getOutfile() markdown := blackfriday.MarkdownBasic(input) if *templatePath != "" { tpl, err := loadTemplate(*templatePath) if err != nil { fmt.Println("Template loading error: %v", err) os.Exit(2) } data := TemplateData{Contents: string(markdown)} err = tpl.Execute(outfile, data) if err != nil { fmt.Println("Template execution error: %v", err) os.Exit(3) } return } _, err := outfile.WriteString(string(markdown)) if err != nil { fmt.Println("Write error: %v", err) } os.Exit(0) }
func (t *Template) load(g *Group, name string, info interface{}) error { t.g = g tmpl := template.New(name) tmpl.Funcs(g.Funcs) var fm map[string]interface{} bytes, err := fmatter.ReadFile(filepath.Join(g.Dir, name), &fm) if err != nil { return err } t.funcMap = template.FuncMap{ "page": func() interface{} { return fm }, } tmpl.Funcs(t.funcMap) ext := filepath.Ext(name) if ext == ".md" { bytes = blackfriday.MarkdownBasic(bytes) } _, err = tmpl.Parse(string(bytes)) if err != nil { return err } t.tmpl = tmpl if l, ok := fm["layout"]; ok { t.layout = l.(string) } else { t.layout = "default" } //writeInfo(info, fm) return nil }
func PreViewArticleHandler(w http.ResponseWriter, r *http.Request) { ctx := GetContext() args := ctx.Args articleMetaData := &ArticleMetaData{} articleMetaData.Author, _ = args["author"].(string) articleMetaData.Title = strings.TrimSpace(r.FormValue("title")) tags := strings.TrimSpace(r.FormValue("tags")) if len(tags) > 0 { tags = strings.Replace(tags, ",", ",", -1) tags = strings.Replace(tags, " ", ",", -1) tag := strings.Split(tags, ",") articleMetaData.Tags = tag } articleMetaData.Summary = r.FormValue("summary") articleMetaData.Content = []byte(r.FormValue("content")) now := time.Now() articleMetaData.PostTime = now articleMetaData.UpdateTime = now articleMetaData.Flag = 1 //article.Flag, _ = strconv.ParseInt(r.FormValue("flag"), 10, 64) articleMetaData.Count = 0 article := &Article{MetaData: *articleMetaData, Text: template.HTML([]byte(blackfriday.MarkdownBasic(articleMetaData.Content)))} data := make(map[string]interface{}) data["article"] = article args["title"] = articleMetaData.Title data["config"] = args viewTPL.ExecuteTemplate(w, "main", data) }
func main() { rawKBZ, kbz := ScrapKBZ(kbz) rawCB, cb := ScrapCB(cb) r := gin.Default() r.GET("/:bank", func(c *gin.Context) { bankName := c.Params.ByName("bank") if bankName == "kbz" { bank := Process(rawKBZ, kbz) c.JSON(200, bank) } else if bankName == "cb" { bank := Process(rawCB, cb) c.JSON(200, bank) } }) r.GET("/", func(c *gin.Context) { body, err := ioutil.ReadFile("README.md") PanicIf(err) c.String(200, string(blackfriday.MarkdownBasic([]byte(body)))) }) r.Run(":" + os.Getenv("PORT")) }
func (t *Thing) EmailParticipants() error { if len(t.Participants) == 0 { return nil } showurl := fmt.Sprint(URL_ROOT, "/show/", t.Id) editurl := fmt.Sprint(URL_ROOT, "/edit/", t.Id) e := email.NewEmail() e.From = t.Owner.Email e.To = []string{} for _, p := range t.Participants { if !p.Done { e.To = append(e.To, p.Email) } } e.Subject = "A friendly reminder..." e.Text = []byte(fmt.Sprintf(texttempl, t.Owner.Email, showurl, t.ThingName, t.ThingLink, editurl)) e.HTML = []byte(blackfriday.MarkdownBasic(e.Text)) fmt.Printf("%v\n", e.To) println(string(e.Text)) return e.Send("MAILHOST:25", nil) // return nil }
// Apply markdown to each section's documentation. func markdownComments(sections []*section) { for _, section := range sections { // IMHO BlackFriday should use a string interface, since it // operates on text (not arbitrary binary) data... section.Doc = string(blackfriday.MarkdownBasic([]byte(section.Doc))) } }
// Fill in Summary and Body values from the Text byte slice. func (this *Article) InflateSummary() { line := bytes.Index(this.Text, []byte("\r\n")) if line == -1 { line = len(this.Text) } this.Summary = string(blackfriday.MarkdownBasic(this.Text[:line])) }
func createPost(file *os.File) (*Post, error) { post := &Post{} var err error = nil reader := bufio.NewReader(file) parse := func(prefix string) string { regex := regexp.MustCompile(prefix + ":") line, _ := reader.ReadString('\n') if match := regex.FindStringIndex(line); match != nil { return strings.TrimSpace(line[match[1] : len(line)-1]) } err = fmt.Errorf("Expected %s string, got : \"%s\"", prefix, line) return "" } post.Title = parse("Title") date := parse("Date") post.Date, err = time.Parse("January 2, 2006", date) post.Filename = path.Base(file.Name()) buffer := bytes.NewBuffer(nil) io.Copy(buffer, reader) post.Content = string(blackfriday.MarkdownBasic(buffer.Bytes())) return post, err }
func (this *TopicController) FileAdd() { this.Ctx.Request.ParseMultipartForm(32 << 20) file, _, err := this.Ctx.Request.FormFile("file") if err != nil { beego.Error("[上传文件错误]" + err.Error()) } defer file.Close() datas, err := ioutil.ReadAll(file) fmt.Println("fmt", datas) if err != nil { beego.Error("[读取文件错误]" + err.Error()) } beego.Info(string(datas) + "[datas]") a := string(datas) result := string(blackfriday.MarkdownBasic(datas)) result = strings.Replace(result, "<code>", "<code class=\"go\">", -1) // this.Ctx.WriteString(string(datas)) 为什么这里不输出 beego.Info(a) this.Data["json"] = result this.ServeJson() }
func saveAllDir(db *mgo.Database, path string) { list, _ := ioutil.ReadDir(path) for _, f := range list { if f.IsDir() && strings.HasPrefix(f.Name(), "2014") { fmt.Println(f.Name()) saveAllDir(db, filepath.Join(path, f.Name())) } else if strings.HasSuffix(f.Name(), ".md") && (strings.HasPrefix(f.Name(), "2015") || strings.HasPrefix(f.Name(), "2014")) { file, err := os.Open(filepath.Join(path, f.Name())) if err != nil { fmt.Println(err) return } defer file.Close() contents, err := ioutil.ReadAll(file) if err != nil { fmt.Println(err) return } unsafe := blackfriday.MarkdownBasic(contents) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) // fmt.Println(string(html)) doc, err := goquery.NewDocumentFromReader(bytes.NewReader(html)) langs := make(map[string]Repos) doc.Find("h4").Each(func(i int, hs *goquery.Selection) { var repos Repos hs.NextUntil("h4").Find("li").Each(func(i int, s *goquery.Selection) { repo := &Repo{} repo.URL, _ = s.Find("a").Attr("href") repo.Name = strings.Replace(strings.Replace(s.Find("a").Text(), " ", "", -1), "\n", "", -1) // repo.Description = parts := strings.Split(s.Text(), ":") repo.Description = strings.TrimSpace(strings.Replace(strings.Join(parts[1:], ""), "\n", "", -1)) img, ok := s.Find("img").Attr("src") if ok { repo.BuiltBy = Contributors{Contributor{ Avatar: img, // Username: "******", }} } repos = append(repos, repo) }) fmt.Println("len:", len(repos)) langs[strings.Title(hs.Text())] = repos }) _, filename := filepath.Split(file.Name()) ymd := strings.Split(strings.TrimSuffix(filename, ".md"), "-") s := &Snapshot{ Date: fmt.Sprintf("%s-%s-%s", ymd[2], ymd[1], ymd[0]), Languages: langs, } s.Save(db) } } }
func main() { m := martini.Classic() m.Post("/generate", func(r *http.Request) []byte { body := r.FormValue("body") return blackfriday.MarkdownBasic([]byte(body)) }) m.Run() }
// Convert converts a byte slice in a particular format to the format's output // (namely HTML) func (f Format) Convert(input []byte) []byte { switch f { case MARKDOWN: return blackfriday.MarkdownBasic(input) default: return input } }
func loadMarkdownPage(title string) ([]byte, error) { filename := title + ".md" body, err := ioutil.ReadFile(filename) if err != nil { return nil, err } output := blackfriday.MarkdownBasic(body) return output, nil }
func writeIndex() { var b bytes.Buffer b.WriteString(getLayout(getSiteTitle())) b.Write(blackfriday.MarkdownBasic(getFile("_sections/header.md"))) writePostsSection(&b) writePagesSection(&b) b.WriteString("</div></body></html>") writeFile("index", b) }
// 保存新增的文章 func (this *TopicDAO) SaveTopic(t *Topic) (int64, error) { content := blackfriday.MarkdownBasic([]byte(t.Content)) t.Content = string(content) t.Content = strings.Replace(t.Content, "<code>", "<code class=\"go\">", -1) t.Created = time.Now().Format("2006-01-02 15:04:05") o := orm.NewOrm() id, err := o.Insert(t) return id, err }
// Load a markdown file's contents into memory func loadFile(title string) (*Page, error) { filename := title + ".md" body, err := ioutil.ReadFile(filename) if err != nil { return nil, err } // Convert the body into markdown mdbody := string(blackfriday.MarkdownBasic(body)[:]) return &Page{Title: title, Body: mdbody}, nil }
func main() { m := martini.Classic() m.Post("/markdown", func(req *http.Request) []byte { body := req.FormValue("content") unsafe := blackfriday.MarkdownBasic([]byte(body)) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) return html }) m.Run() }
func main() { markdown := []byte(` # This is a header * and * this * is * a * list `) html := blackfriday.MarkdownBasic(markdown) fmt.Println(string(html)) }
func renderView(w http.ResponseWriter, p *Page, r *http.Request, markdown bool) { // Get Config from Body var boder = bytes.Split(p.Body, []byte("~![META]!~")) // Replace Body with showable body p.Body = boder[1] if len(boder) > 1 { // Now lets look at the config meta var confer = bytes.Split(boder[0], []byte("::")) // Init some trash vars var public_view = false var public_edit = false // And korrigate them if bytes.Equal(confer[0], []byte("true")) { public_view = true } if bytes.Equal(confer[1], []byte("true")) { public_edit = true } // Get Password var password = strings.TrimSpace(string(confer[2])) // Print Default Body [HEAD PART] fmt.Fprintf(w, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"+ "<head>\n"+ " <title>%s</title>\n"+ " <style type=\"text/css\">%s</style> \n "+ "</head>\n"+ "<body onload=\"document.getElementById('_password').focus();\">\n <div id='header'>\n <div class=\"right\"><a href='/'>%s</a></div>\n <h1><a href=\"/view/%s\">%s</a></h1>\n </div>\n", p.Title+" ~ "+wikiname, css_, wikiname, p.Title, p.Title) if public_view || strings.TrimSpace(r.FormValue("password")) == password { if markdown { p.Body = blackfriday.MarkdownBasic(p.Body) } fmt.Fprintf(w, " <div id='content'>\n%s\n </div>\n", p.Body) fmt.Fprintf(w, " <form action='/edit/%s' >", p.Title) if public_edit { fmt.Fprintf(w, " <div id='edit'><input type='hidden' name='password' value=''><input type='submit' value='Edit »'></div></form>") } else if public_view == false || strings.TrimSpace(r.FormValue("password")) != "" { fmt.Fprintf(w, " <div id='edit'><input type='hidden' name='password' value='%s'><input type='submit' value='Edit »'></div></form>", strings.TrimSpace(r.FormValue("password"))) } else { fmt.Fprintf(w, " <div id='edit'><input type=\"password\" name=\"password\"><input type='submit' value='Edit »'></div></form>") } } else { fmt.Fprintf(w, " <div id='content'><center><div id=\"error\"><div class=\"huge\">[</div><div id='error_container'><div class=\"big\">This Page is not public!</div><br>You think you are the owner?<br><br><form action='/view/%s' ><input type=\"password\" value=\"Password\" onFocus=\"if(this.value == 'Password'){ this.value = ''; }\" name=\"password\" id=\"password\"><input type=\"submit\" value='»'></form></div><div class=\"huge\">]</div></div></center></div>\n", p.Title) } fmt.Fprintf(w, "</body>\n</html>\n") } else { http.Redirect(w, r, "/view/Error", http.StatusFound) } }
func ViewArticleHandler(w http.ResponseWriter, r *http.Request) { ctx := GetContext() ctx.GAEContext = appengine.NewContext(r) beginTime := time.Now() articleMetaData := &ArticleMetaData{} id := r.FormValue("id") if id != "" { articleMetaData.Id = id } else { params := r.URL.Query() year := params.Get(":year") month := params.Get(":month") day := params.Get(":day") title := params.Get(":title") postTime, err := time.Parse("2006-01-02", year+"-"+month+"-"+day) if err != nil { serveError(w, err) return } articleMetaData.PostTime = postTime articleMetaData.UpdateTime = postTime.AddDate(0, 0, 1) articleMetaData.Title = title } err := articleMetaData.GetOne(ctx) if err != nil { http.NotFound(w, r) return } comment := &Comment{ArticleId: articleMetaData.Id} comments, err := comment.GetAll(ctx) if err != nil { serveError(w, err) return } article := &Article{MetaData: *articleMetaData, Comments: comments, Text: template.HTML([]byte(blackfriday.MarkdownBasic(articleMetaData.Content)))} data := make(map[string]interface{}) data["article"] = article endTime := time.Now() ctx.Args["costtime"] = endTime.Sub(beginTime) ctx.Args["title"] = articleMetaData.Title data["args"] = ctx.Args viewTPL.ExecuteTemplate(w, "main", data) }
func render(page string) { log.Println("Rendering", page) content, _ := ioutil.ReadFile(page) content = blackfriday.MarkdownBasic(content) basename := path.Base(page) filename := basename[:strings.LastIndex(basename, ".")] opFile, err := os.Create(path.Join(opDir, filename+".html")) if err != nil { log.Panic(err) } defer opFile.Close() templates.ExecuteTemplate(opFile, "app.html", Page{Content: template.HTML(content)}) }
// RegisterTemplates loads templates from <StaticDir>/email/*.txt into // the global variable t. func RegisterTemplates() (err error) { t = template.New("") t.Funcs(template.FuncMap{ "markdownify": func(s string) template.HTML { return template.HTML( string(blackfriday.MarkdownBasic([]byte(s)))) }, }) t, err = t.ParseGlob(path.Join(StaticDir, "email/*.txt")) return }
func main() { m := martini.Classic() m.Post("/go-bin/martini.cgi", func(r *http.Request) []byte { body := r.FormValue("body") return blackfriday.MarkdownBasic([]byte(body)) }) m.Get("/go-bin/martini.cgi", func(r *http.Request) []byte { body := r.FormValue("body") return blackfriday.MarkdownBasic([]byte(body)) }) m.Run() //http.HandleFunc("/go-bin/quadratic.cgi", m.ServeHTTP) //if err := cgi.Serve(http.HandlerFunc(m.ServeHTTP)); err != nil { // log.Fatal("failed to start server", err) //} }
func main() { m := martini.Classic() m.Post("/parse-github-markdown", func(r *http.Request) []byte { formBody := r.FormValue("parse") return gh.Markdown([]byte(formBody)) }) m.Post("/parse", func(r *http.Request) []byte { formBody := r.FormValue("parse") return blackfriday.MarkdownBasic([]byte(formBody)) }) m.Run() }
func handlePush(conn net.Conn) { data, err := ioutil.ReadAll(conn) if err != nil { log.Println("ERROR", err) return } output := blackfriday.MarkdownBasic(data) key := Save(string(output)) chData <- key }
func CompileMarkdown(path string) ([]byte, error) { dir, err := os.Getwd() if err != nil { log.Println(err) return nil, err } bb, err := ioutil.ReadFile(filepath.Join(dir, path)) if err != nil { log.Println(err) return nil, err } return blackfriday.MarkdownBasic(bb), nil }