Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式。
Markdown具有一系列衍生版本,用于扩展Markdown的功能(如表格、脚注、内嵌HTML等等),这些功能原初的Markdown尚不具备,它们能让Markdown转换成更多的格式,例如LaTeX,Docbook。Markdown增强版中比较有名的有Markdown Extra、MultiMarkdown、 Maruku等。这些衍生版本要么基于工具,如Pandoc;要么基于网站,如GitHub和Wikipedia,在语法上基本兼容,但在一些语法和渲染效果上有改动
使用的库文件
russross/blackfriday
地址:https://github.com/russross/blackfriday
Blackfriday: a markdown processor for Go
package main
import (
"html/template"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"fmt"
"os"
"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) {
if r.URL.Path == "/" {
posts := getPosts()
t := template.New("index.html")
t, _ = t.ParseFiles("index.html")
t.Execute(w, posts)
}else{
file_name:=strings.Replace( r.URL.Path ,"/","",1)
var file string
if strings.Contains(file_name,".md"){
file=fmt.Sprintf("Golang/%s",string(file_name))
}else{
file=fmt.Sprintf("Golang/%s.md",string(file_name))
}
_,err:=os.Stat(file)
if err!=nil{
fmt.Println(err)
w.WriteHeader(404)
return
}
txt,err:=ioutil.ReadFile(file)
output := blackfriday.MarkdownCommon(txt)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type:text/html", "charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Action, Module") //有使用自定义头 需要这个,Action, Module是例子
fmt.Fprint(w,string(output))
//w.Write(output)
}
}
func getPosts() []Post {
a := []Post{}
files, _ := filepath.Glob("Golang/*.md")
fmt.Println(files)
for _, f := range files {
file := strings.Replace(f, "Golang\\", "", -1)
fmt.Println(file)
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)
}