-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_posts.go
48 lines (34 loc) · 900 Bytes
/
handler_posts.go
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
package handler
import (
"encoding/json"
"net/http"
"github.com/kallydev/c10k/internal/database/model"
"github.com/valyala/fasthttp"
)
type GetPostListErrorResponse struct {
Error string `json:"error"`
}
func (h *Handler) GetPostList(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json")
rows, err := h.DB.Queryx("SELECT * FROM posts;")
if err != nil {
ctx.SetStatusCode(http.StatusInternalServerError)
_ = json.NewEncoder(ctx).Encode(&GetPostListErrorResponse{
Error: err.Error(),
})
return
}
var posts = make([]model.Post, 0)
for rows.Next() {
var post model.Post
if err := rows.StructScan(&post); err != nil {
ctx.SetStatusCode(http.StatusInternalServerError)
_ = json.NewEncoder(ctx).Encode(&GetPostListErrorResponse{
Error: err.Error(),
})
return
}
posts = append(posts, post)
}
_ = json.NewEncoder(ctx).Encode(posts)
}