implement endpoints to create and query all blog articles

Signed-off-by: Tobias Erbshäußer <tobias@tesoft.dev>
This commit is contained in:
2026-05-24 09:22:22 +02:00
parent 13cdbe249b
commit 4f770d01d8
2 changed files with 129 additions and 8 deletions
+97
View File
@@ -149,3 +149,100 @@ func ParseArticle(reader io.Reader, filePrefix string) (*Article, error) {
files,
}, nil
}
func (h *ApiHandler) ServeBlogGet(writer http.ResponseWriter, request *http.Request) {
query := request.URL.Query()
var err error
var offset int
var limit int
offsetStr := query.Get("offset")
if offsetStr == "" {
offset = 0
} else {
offset, err = strconv.Atoi(offsetStr)
if err != nil || offset < 0 {
http.Error(writer, "invalid offset", http.StatusBadRequest)
return
}
}
limitStr := query.Get("limit")
if limitStr == "" {
limit = 50
} else {
limit, err = strconv.Atoi(limitStr)
if err != nil || limit <= 0 || limit > 100 {
http.Error(writer, "invalid limit", http.StatusBadRequest)
return
}
}
articles, err := h.db.GetBlogArticles(IsAuthorized(request), offset, limit)
if err != nil {
log.Println("Error getting articles:", err)
http.Error(writer, "failed to query database", http.StatusInternalServerError)
return
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
err = json.NewEncoder(writer).Encode(articles)
if err != nil {
http.Error(writer, "failed to serialize results", http.StatusInternalServerError)
}
}
func (h *ApiHandler) ServeBlogPut(writer http.ResponseWriter, request *http.Request) {
err := request.ParseMultipartForm(10 * 1024 * 1024)
if err != nil {
http.Error(writer, "failed to parse multipart form", http.StatusBadRequest)
return
}
file, _, err := request.FormFile("file")
if err != nil {
http.Error(writer, "failed to parse file", http.StatusBadRequest)
return
}
defer func() {
_ = file.Close()
}()
log.Println("Creating new blog article")
id, commit, err := h.db.CreateBlogArticle()
if err != nil {
log.Println("Error creating new blog article:", err)
http.Error(writer, "failed to add article to database", http.StatusInternalServerError)
return
}
article, err := ParseArticle(file, "/api/blog/"+strconv.FormatInt(id, 10)+"/file/")
if err != nil {
_ = commit(nil)
log.Println("Error creating new blog article:", err)
http.Error(writer, "failed to add article to database", http.StatusInternalServerError)
return
}
err = commit(article)
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
err = json.NewEncoder(writer).Encode(map[string]interface{}{
"id": id,
})
if err != nil {
http.Error(writer, "failed to serialize results", http.StatusInternalServerError)
}
}
func (h *ApiHandler) ServeBlogGetSingle(writer http.ResponseWriter, request *http.Request) {
// TODO
}
func (h *ApiHandler) ServeBlogFileGetSingle(writer http.ResponseWriter, request *http.Request) {
// TODO
}