aboutsummaryrefslogtreecommitdiff
path: root/cmd/http/load.go
blob: 6e0c0319db0ef60823136b0dab62b01372962594 (plain) (blame)
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
91
92
93
94
95
96
97
98
package main

import (
	"errors"
	"os"
	"sort"
	"strings"
)

// Post struct contains necessary data for a post
type Post struct {
	File  string
	Title string
	Date  string
	Tags  []string
}

// Read all found files and load them into a stuct
func (app *application) aggregate(location string) (p []*Post, err error) {
	var posts []*Post

	files, err := os.ReadDir(location)
	if err != nil {
		return nil, err
	}

	// Loop over every file in the directory and read the contents.
	for _, file := range files {
		if !file.IsDir() && strings.HasSuffix(file.Name(), ".tmpl.html") {
			newPost := app.parseFileName(strings.TrimSuffix(file.Name(), ".tmpl.html"))

			posts = append(posts, newPost)
		}
	}

	sort.Slice(posts, func(i, j int) bool {
		return posts[i].Date > posts[j].Date
	})

	return posts, nil
}

func (app *application) parseFileName(file string) (p *Post) {
	var post *Post = new(Post)

	svList := strings.Split(file, "+")
	usvLength := len(svList)

	// date
	/*datePattern := regexp.MustCompile(`{{define "uploaded-on"}}(\d{4}-\d{2}-\d{2}){{end}}`)
	dateMatching := datePattern.FindStringSubmatch(string(fileContent))

	//var date string
	if len(dateMatching) > 1 {
		date = dateMatching[1]
	} else {
		date = ""
	}*/
	date := svList[0]

	// title
	title := strings.ReplaceAll(svList[1], "_", " ")

	// tags
	/*tagsPattern := regexp.MustCompile(`{{define "keywords"}}([\w\s]+){{end}}`)
	matchingTags := tagsPattern.FindStringSubmatch(string(fileContent))

	var tags []string
	if len(matchingTags) > 1 {
		tags = strings.Fields(matchingTags[1])
	} else {
		tags = []string{}
	}*/

	var tags []string
	if usvLength > 2 {
		for i := 2; i < usvLength; i++ {
			tags = append(tags, svList[i])
		}
	} else {
		tags = []string{}
	}

	post.File = file
	post.Title = title
	post.Date = date
	post.Tags = tags

	return post

}

func (app *application) fileExists(file string) bool {
	if _, err := os.Stat(file); errors.Is(err, os.ErrNotExist) {
		return false
	}
	return true
}