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 } // Posts stuct contains a collection of type Post type Posts struct { Collection []*Post } // Read all found files and load them into a stuct func (app *application) aggregate(location string) (p *Posts, 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{Collection: 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 }