-
Notifications
You must be signed in to change notification settings - Fork 0
/
article.go
90 lines (69 loc) · 2.22 KB
/
article.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"bytes"
"github.com/russross/blackfriday"
"html/template"
"io/ioutil"
"path/filepath"
"regexp"
"sort"
"time"
)
type Article struct {
Metadata *Metadata
Content template.HTML
}
type Metadata struct {
Title string
Slug string
Description string
Date time.Time
Tags string
HeroImage string
}
type ArticleList []*Article
func (a ArticleList) Len() int { return len(a) }
func (a ArticleList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ArticleList) Less(i, j int) bool { return a[i].Metadata.Date.After(a[j].Metadata.Date) }
func LoadArticles() ArticleList {
files, _ := filepath.Glob("articles/*.md")
articles := make(ArticleList, len(files))
for i, filename := range files {
article := parseArticle(filename)
articles[i] = article
}
sort.Sort(articles)
return articles
}
func parseArticle(filename string) *Article {
fileContent, _ := ioutil.ReadFile(filename)
metadata, content := parseFileContent(fileContent)
return &Article{Metadata: metadata, Content: content}
}
func parseFileContent(content []byte) (*Metadata, template.HTML) {
splited := bytes.Split(content, []byte("---"))
return parseMetadata(splited[1]), parseBody(splited[2])
}
func parseMetadata(metadata []byte) *Metadata {
titleRegex := regexp.MustCompile("title:\\s(.+)")
title := titleRegex.FindStringSubmatch(string(metadata))[1]
descriptionRegex := regexp.MustCompile("description:\\s(.+)")
description := descriptionRegex.FindStringSubmatch(string(metadata))[1]
dateRegex := regexp.MustCompile("date:\\s(.+)")
date := dateRegex.FindStringSubmatch(string(metadata))[1]
parsedDate, _ := time.Parse("2006-01-02", date)
tagsRegex := regexp.MustCompile("tags:\\s(.+)")
tags := tagsRegex.FindStringSubmatch(string(metadata))[1]
slugRegex := regexp.MustCompile("slug:\\s(.+)")
slug := slugRegex.FindStringSubmatch(string(metadata))[1]
return &Metadata{
Title: title,
Slug: slug,
Description: description,
Date: parsedDate,
Tags: tags}
}
func parseBody(content []byte) template.HTML {
parsedMarkdown := blackfriday.MarkdownCommon(content)
return template.HTML(parsedMarkdown)
}