blogposts: read metadata

This commit is contained in:
vinchent 2024-09-24 21:26:42 +02:00
parent 00596a7c52
commit a33d490896
2 changed files with 29 additions and 9 deletions

View File

@ -17,9 +17,16 @@ import (
// }
func TestNewBlogPosts(t *testing.T) {
const (
firstBody = `Title: Post 1
Description: Description 1`
secondBody = `Title: Post 2
Description: Description 2`
)
fs := fstest.MapFS{
"hello world.md": {Data: []byte("Title: Post 1")},
"hello-world2.md": {Data: []byte("Title: Post 2")},
"hello world.md": {Data: []byte(firstBody)},
"hello-world2.md": {Data: []byte(secondBody)},
}
posts, err := NewPostsFromFS(fs)
@ -31,9 +38,10 @@ func TestNewBlogPosts(t *testing.T) {
t.Errorf("got %d posts, wanted %d posts", len(posts), len(fs))
}
got := posts[0]
want := Post{Title: "Post 1"}
assertPost(t, got, want)
assertPost(t, posts[0], Post{
Title: "Post 1",
Description: "Description 1",
})
}
func assertPost(t testing.TB, got Post, want Post) {

View File

@ -1,8 +1,10 @@
package blogposts
import (
"bufio"
"io"
"io/fs"
"strings"
)
type Post struct {
@ -10,6 +12,11 @@ type Post struct {
Tags []string
}
const (
titleSeparator = "Title: "
descriptionSeparator = "Description: "
)
func getPost(fileSystem fs.FS, fileName string) (Post, error) {
postFile, err := fileSystem.Open(fileName)
if err != nil {
@ -23,11 +30,16 @@ func getPost(fileSystem fs.FS, fileName string) (Post, error) {
// NOTE: Does newPost have to be coupled to an fs.File ?
// Do we use all the methods and data from this type? What do we really need?
func newPost(postFile io.Reader) (Post, error) {
postData, err := io.ReadAll(postFile)
if err != nil {
return Post{}, err
scanner := bufio.NewScanner(postFile)
readMetaLine := func(tagName string) string {
scanner.Scan()
return strings.TrimPrefix(scanner.Text(), tagName)
}
post := Post{Title: string(postData)[7:]}
post := Post{
Title: readMetaLine(titleSeparator),
Description: readMetaLine(descriptionSeparator),
}
return post, nil
}