feat: allow to write to notes
This commit is contained in:
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@@ -10,6 +11,7 @@ type ErrorResponse struct {
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, code int, err error) {
|
||||
log.Printf("error: %s", err)
|
||||
writeJSON(w, code, ErrorResponse{Error: err.Error()})
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,12 @@ package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.max-richter.dev/max/marka/renderer"
|
||||
"git.max-richter.dev/max/marka/server/internal/adapters"
|
||||
)
|
||||
|
||||
@@ -44,7 +48,35 @@ func (h *Handler) get(w http.ResponseWriter, target string) {
|
||||
writeError(w, http.StatusInternalServerError, errors.New("unknown entry type"))
|
||||
}
|
||||
|
||||
func (h *Handler) post(w http.ResponseWriter, target string) {
|
||||
func (h *Handler) post(w http.ResponseWriter, r *http.Request, target string) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
isJSON := strings.HasPrefix(contentType, "application/json")
|
||||
|
||||
var contentToWrite []byte
|
||||
if strings.HasSuffix(target, ".md") && isJSON {
|
||||
renderedContent, err := renderer.RenderFile(body)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, fmt.Errorf("failed to render file: %w", err))
|
||||
return
|
||||
}
|
||||
contentToWrite = renderedContent
|
||||
} else {
|
||||
contentToWrite = body
|
||||
}
|
||||
|
||||
if err := h.adapter.Write(target, contentToWrite); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, fmt.Errorf("failed to write file: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -59,7 +91,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case http.MethodGet:
|
||||
h.get(w, target)
|
||||
case http.MethodPost:
|
||||
h.post(w, target)
|
||||
h.post(w, r, target)
|
||||
default:
|
||||
writeError(w, http.StatusMethodNotAllowed, errors.New("method not allowed"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user