blogposts: create new file for post and a helper func

This commit is contained in:
vinchent 2024-09-24 21:10:16 +02:00
parent 1153a0a5bd
commit 00596a7c52
3 changed files with 37 additions and 28 deletions

View File

@ -1,15 +1,9 @@
package blogposts
import (
"io"
"io/fs"
)
type Post struct {
Title, Description, Body string
Tags []string
}
func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
dir, err := fs.ReadDir(fileSystem, ".")
if err != nil {
@ -25,25 +19,3 @@ func NewPostsFromFS(fileSystem fs.FS) ([]Post, error) {
}
return posts, nil
}
func getPost(fileSystem fs.FS, fileName string) (Post, error) {
postFile, err := fileSystem.Open(fileName)
if err != nil {
return Post{}, err
}
defer postFile.Close()
return newPost(postFile)
}
// 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
}
post := Post{Title: string(postData)[7:]}
return post, nil
}

View File

@ -33,7 +33,11 @@ func TestNewBlogPosts(t *testing.T) {
got := posts[0]
want := Post{Title: "Post 1"}
assertPost(t, got, want)
}
func assertPost(t testing.TB, got Post, want Post) {
t.Helper()
if !reflect.DeepEqual(got, want) {
t.Errorf("got %+v, want %+v", got, want)
}

33
blogposts/post.go Normal file
View File

@ -0,0 +1,33 @@
package blogposts
import (
"io"
"io/fs"
)
type Post struct {
Title, Description, Body string
Tags []string
}
func getPost(fileSystem fs.FS, fileName string) (Post, error) {
postFile, err := fileSystem.Open(fileName)
if err != nil {
return Post{}, err
}
defer postFile.Close()
return newPost(postFile)
}
// 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
}
post := Post{Title: string(postData)[7:]}
return post, nil
}