Skip to content

Commit

Permalink
feat: initial GET blog
Browse files Browse the repository at this point in the history
  • Loading branch information
EYssel committed Feb 23, 2024
1 parent 8bff7df commit d3a5234
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 9 deletions.
12 changes: 6 additions & 6 deletions blogs/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ func (m MemStore) Get(id uuid.UUID) (Blog, error) {
return Blog{}, NotFoundErr
}

func (m MemStore) List() ([]Blog, error) {
func (m MemStore) List() (map[uuid.UUID]Blog, error) {

var blogs []Blog
// var blogs []Blog

for _, item := range m.list {
blogs = append(blogs, item)
}
// for _, item := range m.list {
// blogs = append(blogs, item)
// }

return blogs, nil
return m.list, nil
}

func (m MemStore) Update(id uuid.UUID, blog Blog) error {
Expand Down
48 changes: 45 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,55 @@ func (h *BlogsHandler) ListBlogs(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(jsonBytes)
}
func (h *BlogsHandler) GetBlog(w http.ResponseWriter, r *http.Request) {}
func (h *BlogsHandler) GetBlog(w http.ResponseWriter, r *http.Request) {
// Extract the resource ID/slug using a regex
matches := BlogReWithID.FindStringSubmatch(r.URL.Path)
// Expect matches to be length >= 2 (full string + 1 matching group)
if len(matches) < 2 {
InternalServerErrorHandler(w, r)
return
}

id, err := uuid.Parse(matches[1])
fmt.Print("Getting Blog")
fmt.Print(id)

if err != nil {
InternalServerErrorHandler(w, r)
return
}

// Retrieve blog from the store
blog, err := h.store.Get(id)
if err != nil {
// Special case of NotFound Error
if err == blogs.NotFoundErr {
NotFoundHandler(w, r)
return
}

// Every other error
InternalServerErrorHandler(w, r)
return
}

// Convert the struct into JSON payload
jsonBytes, err := json.Marshal(blog)
if err != nil {
InternalServerErrorHandler(w, r)
return
}

// Write the results
w.WriteHeader(http.StatusOK)
w.Write(jsonBytes)
}
func (h *BlogsHandler) UpdateBlog(w http.ResponseWriter, r *http.Request) {}
func (h *BlogsHandler) DeleteBlog(w http.ResponseWriter, r *http.Request) {}

var (
BlogRe = regexp.MustCompile(`^/blogs/*$`)
BlogReWithID = regexp.MustCompile(`^/blogs/([a-z0-9]+(?:-[a-z0-9]+)+)$`)
BlogReWithID = regexp.MustCompile(`^/blogs/([a-z0-9])$`)
)

func (h *BlogsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -113,7 +155,7 @@ type blogStore interface {
Add(blog blogs.Blog) error
Get(id uuid.UUID) (blogs.Blog, error)
Update(id uuid.UUID, blog blogs.Blog) error
List() ([]blogs.Blog, error)
List() (map[uuid.UUID]blogs.Blog, error)
Remove(id uuid.UUID) error
}

Expand Down

0 comments on commit d3a5234

Please sign in to comment.