feat: implement WYSIWYG markdown editor
Add complete markdown editor with Go backend and React/TypeScript frontend. Backend: - Cobra CLI with configurable host, port, data-dir, static-dir flags - REST API for CRUD operations on markdown files (GET, POST, PUT, DELETE) - File storage with flat .md structure - Comprehensive Logrus logging for all operations - Static asset serving for frontend Frontend: - React 18 + TypeScript + Tailwind CSS - Live markdown editor with GFM preview (react-markdown) - File management UI (list, create, open, save, delete) - Theme system (Light/Dark/System) with localStorage persistence - Responsive design (320px - 1920px+) Testing: - 6 backend tests covering CRUD round-trip, validation, error handling - 19 frontend tests covering API, theme system, and UI components - All tests passing with single 'make test' command Build: - Frontend compiles to optimized assets in dist/ - Backend can serve frontend via --static-dir flag
This commit is contained in:
171
backend/internal/api/handlers.go
Normal file
171
backend/internal/api/handlers.go
Normal file
@@ -0,0 +1,171 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
"github.com/evanreichard/markdown-editor/internal/storage"
|
||||
)
|
||||
|
||||
// Handlers contains the HTTP handlers
|
||||
type Handlers struct {
|
||||
storage *storage.Storage
|
||||
}
|
||||
|
||||
// New creates a new Handlers instance
|
||||
func New(s *storage.Storage) *Handlers {
|
||||
logging.Logger.Info("API handlers initialized")
|
||||
return &Handlers{storage: s}
|
||||
}
|
||||
|
||||
// ErrorResponse represents an error response
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// sendError sends a JSON error response
|
||||
func (h *Handlers) sendError(w http.ResponseWriter, r *http.Request, statusCode int, err error) {
|
||||
logging.Logger.WithFields(map[string]interface{}{
|
||||
"path": r.URL.Path,
|
||||
"status": statusCode,
|
||||
"error": err.Error(),
|
||||
}).Warn("API error")
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: err.Error()})
|
||||
}
|
||||
|
||||
// ListFiles handles GET /api/files
|
||||
func (h *Handlers) ListFiles(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
h.sendError(w, r, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
files, err := h.storage.List()
|
||||
if err != nil {
|
||||
h.sendError(w, r, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(files)
|
||||
}
|
||||
|
||||
// GetFile handles GET /api/files/:name
|
||||
func (h *Handlers) GetFile(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
h.sendError(w, r, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(r.URL.Path, "/api/files/")
|
||||
if name == "" {
|
||||
h.sendError(w, r, http.StatusBadRequest, fmt.Errorf("file name required"))
|
||||
return
|
||||
}
|
||||
|
||||
file, err := h.storage.Get(name)
|
||||
if err != nil {
|
||||
if err == storage.ErrFileNotFound {
|
||||
h.sendError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
h.sendError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(file)
|
||||
}
|
||||
|
||||
// CreateFile handles POST /api/files
|
||||
func (h *Handlers) CreateFile(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
h.sendError(w, r, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
var file storage.File
|
||||
if err := json.NewDecoder(r.Body).Decode(&file); err != nil {
|
||||
h.sendError(w, r, http.StatusBadRequest, fmt.Errorf("invalid request body: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.storage.Create(file.Name, file.Content)
|
||||
if err != nil {
|
||||
if err == storage.ErrInvalidName {
|
||||
h.sendError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
h.sendError(w, r, http.StatusConflict, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
|
||||
// UpdateFile handles PUT /api/files/:name
|
||||
func (h *Handlers) UpdateFile(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut {
|
||||
h.sendError(w, r, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(r.URL.Path, "/api/files/")
|
||||
if name == "" {
|
||||
h.sendError(w, r, http.StatusBadRequest, fmt.Errorf("file name required"))
|
||||
return
|
||||
}
|
||||
|
||||
var file storage.File
|
||||
if err := json.NewDecoder(r.Body).Decode(&file); err != nil {
|
||||
h.sendError(w, r, http.StatusBadRequest, fmt.Errorf("invalid request body: %w", err))
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.storage.Update(name, file.Content)
|
||||
if err != nil {
|
||||
if err == storage.ErrFileNotFound {
|
||||
h.sendError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
h.sendError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
|
||||
// DeleteFile handles DELETE /api/files/:name
|
||||
func (h *Handlers) DeleteFile(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodDelete {
|
||||
h.sendError(w, r, http.StatusMethodNotAllowed, fmt.Errorf("method not allowed"))
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(r.URL.Path, "/api/files/")
|
||||
if name == "" {
|
||||
h.sendError(w, r, http.StatusBadRequest, fmt.Errorf("file name required"))
|
||||
return
|
||||
}
|
||||
|
||||
err := h.storage.Delete(name)
|
||||
if err != nil {
|
||||
if err == storage.ErrFileNotFound {
|
||||
h.sendError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
h.sendError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
24
backend/internal/config/config.go
Normal file
24
backend/internal/config/config.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package config
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Config holds the server configuration
|
||||
type Config struct {
|
||||
DataDir string
|
||||
Port string
|
||||
Host string
|
||||
}
|
||||
|
||||
// Default returns the default configuration
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
DataDir: "./data",
|
||||
Port: "8080",
|
||||
Host: "127.0.0.1",
|
||||
}
|
||||
}
|
||||
|
||||
// Addr returns the full address to bind to
|
||||
func (c *Config) Addr() string {
|
||||
return fmt.Sprintf("%s:%s", c.Host, c.Port)
|
||||
}
|
||||
37
backend/internal/logging/logger.go
Normal file
37
backend/internal/logging/logger.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var Logger *logrus.Logger
|
||||
|
||||
// Init initializes the logger
|
||||
func Init() {
|
||||
Logger = logrus.New()
|
||||
Logger.SetFormatter(&logrus.JSONFormatter{})
|
||||
Logger.SetLevel(logrus.InfoLevel)
|
||||
}
|
||||
|
||||
// RequestMiddleware logs HTTP requests
|
||||
func RequestMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
Logger.WithFields(logrus.Fields{
|
||||
"method": r.Method,
|
||||
"path": r.URL.Path,
|
||||
}).Info("Request started")
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
Logger.WithFields(logrus.Fields{
|
||||
"method": r.Method,
|
||||
"path": r.URL.Path,
|
||||
"duration": time.Since(start).String(),
|
||||
}).Info("Request completed")
|
||||
})
|
||||
}
|
||||
34
backend/internal/router/router.go
Normal file
34
backend/internal/router/router.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/api"
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
)
|
||||
|
||||
// New creates a new HTTP router with all routes configured
|
||||
func New(handlers *api.Handlers, staticDir string) *http.ServeMux {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// API routes
|
||||
mux.HandleFunc("GET /api/files", handlers.ListFiles)
|
||||
mux.HandleFunc("GET /api/files/", handlers.GetFile)
|
||||
mux.HandleFunc("POST /api/files", handlers.CreateFile)
|
||||
mux.HandleFunc("PUT /api/files/", handlers.UpdateFile)
|
||||
mux.HandleFunc("DELETE /api/files/", handlers.DeleteFile)
|
||||
|
||||
// Static assets
|
||||
if staticDir != "" {
|
||||
logging.Logger.WithField("static_dir", staticDir).Info("Static assets configured")
|
||||
fs := http.FileServer(http.Dir(staticDir))
|
||||
mux.Handle("/", fs)
|
||||
} else {
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "Static assets directory not configured", http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
logging.Logger.Info("Router initialized with all routes")
|
||||
return mux
|
||||
}
|
||||
173
backend/internal/storage/storage.go
Normal file
173
backend/internal/storage/storage.go
Normal file
@@ -0,0 +1,173 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFileNotFound = errors.New("file not found")
|
||||
ErrInvalidName = errors.New("invalid file name")
|
||||
)
|
||||
|
||||
// File represents a markdown file
|
||||
type File struct {
|
||||
Name string `json:"name"`
|
||||
Content string `json:"content"`
|
||||
Modified int64 `json:"modified"`
|
||||
}
|
||||
|
||||
// Storage handles file operations
|
||||
type Storage struct {
|
||||
dataDir string
|
||||
}
|
||||
|
||||
// New creates a new Storage instance
|
||||
func New(dataDir string) (*Storage, error) {
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory: %w", err)
|
||||
}
|
||||
logging.Logger.WithField("data_dir", dataDir).Info("Storage initialized")
|
||||
return &Storage{dataDir: dataDir}, nil
|
||||
}
|
||||
|
||||
// List returns all markdown files
|
||||
func (s *Storage) List() ([]*File, error) {
|
||||
entries, err := os.ReadDir(s.dataDir)
|
||||
if err != nil {
|
||||
logging.Logger.WithError(err).Error("Failed to list files")
|
||||
return nil, fmt.Errorf("failed to read directory: %w", err)
|
||||
}
|
||||
|
||||
var files []*File
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
|
||||
continue
|
||||
}
|
||||
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
files = append(files, &File{
|
||||
Name: entry.Name(),
|
||||
Modified: info.ModTime().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
logging.Logger.WithField("count", len(files)).Info("Listed files")
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// Get reads a markdown file
|
||||
func (s *Storage) Get(name string) (*File, error) {
|
||||
if !s.isValidName(name) {
|
||||
logging.Logger.WithField("name", name).Warn("Invalid file name")
|
||||
return nil, ErrInvalidName
|
||||
}
|
||||
|
||||
path := filepath.Join(s.dataDir, name)
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
logging.Logger.WithField("name", name).Warn("File not found")
|
||||
return nil, ErrFileNotFound
|
||||
}
|
||||
logging.Logger.WithError(err).Error("Failed to read file")
|
||||
return nil, fmt.Errorf("failed to read file: %w", err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get file info: %w", err)
|
||||
}
|
||||
|
||||
logging.Logger.WithField("name", name).Info("File retrieved")
|
||||
return &File{
|
||||
Name: name,
|
||||
Content: string(content),
|
||||
Modified: info.ModTime().Unix(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Create creates a new markdown file
|
||||
func (s *Storage) Create(name, content string) (*File, error) {
|
||||
if !s.isValidName(name) {
|
||||
logging.Logger.WithField("name", name).Warn("Invalid file name for create")
|
||||
return nil, ErrInvalidName
|
||||
}
|
||||
|
||||
path := filepath.Join(s.dataDir, name)
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
logging.Logger.WithField("name", name).Warn("File already exists")
|
||||
return nil, fmt.Errorf("file already exists")
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
||||
logging.Logger.WithError(err).Error("Failed to create file")
|
||||
return nil, fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
|
||||
logging.Logger.WithField("name", name).Info("File created")
|
||||
return s.Get(name)
|
||||
}
|
||||
|
||||
// Update updates an existing markdown file
|
||||
func (s *Storage) Update(name, content string) (*File, error) {
|
||||
if !s.isValidName(name) {
|
||||
logging.Logger.WithField("name", name).Warn("Invalid file name for update")
|
||||
return nil, ErrInvalidName
|
||||
}
|
||||
|
||||
path := filepath.Join(s.dataDir, name)
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
logging.Logger.WithField("name", name).Warn("File not found for update")
|
||||
return nil, ErrFileNotFound
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
|
||||
logging.Logger.WithError(err).Error("Failed to update file")
|
||||
return nil, fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
|
||||
logging.Logger.WithField("name", name).Info("File updated")
|
||||
return s.Get(name)
|
||||
}
|
||||
|
||||
// Delete removes a markdown file
|
||||
func (s *Storage) Delete(name string) error {
|
||||
if !s.isValidName(name) {
|
||||
logging.Logger.WithField("name", name).Warn("Invalid file name for delete")
|
||||
return ErrInvalidName
|
||||
}
|
||||
|
||||
path := filepath.Join(s.dataDir, name)
|
||||
if err := os.Remove(path); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
logging.Logger.WithField("name", name).Warn("File not found for delete")
|
||||
return ErrFileNotFound
|
||||
}
|
||||
logging.Logger.WithError(err).Error("Failed to delete file")
|
||||
return fmt.Errorf("failed to delete file: %w", err)
|
||||
}
|
||||
|
||||
logging.Logger.WithField("name", name).Info("File deleted")
|
||||
return nil
|
||||
}
|
||||
|
||||
// isValidName checks if the file name is valid
|
||||
func (s *Storage) isValidName(name string) bool {
|
||||
if name == "" || strings.Contains(name, "..") || strings.Contains(name, "/") {
|
||||
return false
|
||||
}
|
||||
if !strings.HasSuffix(name, ".md") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user