生命不止,继续 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 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
关于如何使用html/template,请参考博客:
Go语言学习之html/template包(The way to go)
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)
}
<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)
}