這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
生命不止,繼續 go go go !!!
先來一點小小的插曲,部落格關於go的uv量:
今天,跟大家一起學習分享的是在golang中如何使用markdown文法,當然是使用第三方庫了russross/blackfriday。
參考:http://blog.will3942.com/creating-blog-go
markdown
Markdown是一種可以使用普通文字編輯器編寫的標記語言,通過簡單的標記文法,它可以使普通常值內容具有一定的格式。
Markdown具有一系列衍生版本,用於擴充Markdown的功能(如表格、腳註、內嵌HTML等等),這些功能原初的Markdown尚不具備,它們能讓Markdown轉換成更多的格式,例如LaTeX,Docbook。Markdown增強版中比較有名的有Markdown Extra、MultiMarkdown、 Maruku等。這些衍生版本要麼基於工具,如Pandoc;要麼基於網站,如GitHub和Wikipedia,在文法上基本相容,但在一些文法和渲染效果上有改動
這裡怒推一款好用的markdown編輯軟體:
Haroopad–最好用的markdown編輯器
russross/blackfriday
地址:https://github.com/russross/blackfriday
也是在golang中,最有名的吧
Blackfriday: a markdown processor for Go
watch:72
star:2591
fork:328
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 mainimport ( "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
關於如何使用html/template,請參考部落格:
Go語言學習之html/template包(The way to go)
index.html:
<html> <body> <h1>SuperWang's Blog!</h1> <p>{{.}}</p> </body></html>
package mainimport ( "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檔案
index.html修改為:
<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/2017This is the summary.This is the main post!# Markdown!*it's* **golang**!
main.go:
package mainimport ( "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, _ = t.ParseFiles("index.html") t.Execute(w, 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)}