Go实战--golang中使用markdown(russross/blackfriday)
生命不止,继续 go go go !!! 先来一点小小的插曲,博客关于go的uv量: 今天,跟大家一起学习分享的是在golang中如何使用markdown语法,当然是使用第三方库了russross/blackfriday。 markdownMarkdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式。 这里怒推一款好用的markdown编辑软件: russross/blackfriday地址:https://github.com/russross/blackfriday Blackfriday is a Markdown processor implemented in Go. It is paranoid about its input (so you can safely feed it user-supplied data),it is fast,it supports common extensions (tables,smart punctuation substitutions,etc.),and it is safe for all utf-8 (unicode) input. 一个简单的server package main
import (
"fmt"
"net/http"
)
func handlerequest(w http.ResponseWriter,r *http.Request) {
fmt.Fprintf(w,"Hi i am SuperWang %s",r.URL.Path[1:])
}
func main() {
http.HandleFunc("/",handlerequest)
http.ListenAndServe(":8000",nil)
}
使用template index.html: <html>
<body>
<h1>SuperWang's Blog!</h1> <p>{{.}}</p> </body> </html>
package main
import (
"html/template"
"net/http"
)
func handlerequest(w http.ResponseWriter,r *http.Request) {
title := "Hello Golang World!"
t := template.New("index.html")
t,_ = t.ParseFiles("index.html")
t.Execute(w,title)
}
func main() {
http.HandleFunc("/",handlerequest)
http.ListenAndServe(":8000",nil)
}
读取markdown文件 <html> <body> <h1>SuperWang's Blog!</h1> {{range .}} <a href="/{{.File}}"><h2>{{.Title}} ({{.Date}})</h2></a> <p>{{.Summary}}</p> {{end}} </body> </html>
md文件,姑且命名为test.md: First post!
8/9/2017
This is the summary.
This is the main post!
# Markdown!
*it's* **golang**!
main.go: package main
import (
"html/template"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"github.com/russross/blackfriday"
)
type Post struct {
Title string
Date string
Summary string
Body string
File string
}
func handlerequest(w http.ResponseWriter,r *http.Request) {
posts := getPosts()
t := template.New("index.html")
t,posts)
}
func getPosts() []Post {
a := []Post{}
files,_ := filepath.Glob("posts/*")
for _,f := range files {
file := strings.Replace(f,"posts/","",-1)
file = strings.Replace(file,".md",-1)
fileread,_ := ioutil.ReadFile(f)
lines := strings.Split(string(fileread),"n")
title := string(lines[0])
date := string(lines[1])
summary := string(lines[2])
body := strings.Join(lines[3:len(lines)],"n")
body = string(blackfriday.MarkdownCommon([]byte(body)))
a = append(a,Post{title,date,summary,body,file})
}
return a
}
func main() {
http.HandleFunc("/",handlerequest)
http.ListenAndServe(":8000",nil)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |