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:
80
backend/cmd/server/root.go
Normal file
80
backend/cmd/server/root.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/api"
|
||||
"github.com/evanreichard/markdown-editor/internal/config"
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
"github.com/evanreichard/markdown-editor/internal/router"
|
||||
"github.com/evanreichard/markdown-editor/internal/storage"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var (
|
||||
dataDir string
|
||||
port string
|
||||
host string
|
||||
staticDir string
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "server",
|
||||
Short: "Markdown editor server",
|
||||
Long: "A markdown editor server with REST API and frontend support",
|
||||
Run: runServer,
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.Flags().StringVar(&dataDir, "data-dir", "./data", "Storage path for markdown files")
|
||||
rootCmd.Flags().StringVar(&port, "port", "8080", "Server port")
|
||||
rootCmd.Flags().StringVar(&host, "host", "127.0.0.1", "Bind address")
|
||||
rootCmd.Flags().StringVar(&staticDir, "static-dir", "./frontend/dist", "Path to static assets")
|
||||
}
|
||||
|
||||
func runServer(cmd *cobra.Command, args []string) {
|
||||
cfg := &config.Config{
|
||||
DataDir: dataDir,
|
||||
Port: port,
|
||||
Host: host,
|
||||
}
|
||||
|
||||
logging.Init()
|
||||
logging.Logger.WithFields(map[string]interface{}{
|
||||
"data_dir": cfg.DataDir,
|
||||
"host": cfg.Host,
|
||||
"port": cfg.Port,
|
||||
"static_dir": staticDir,
|
||||
}).Info("Starting markdown editor server")
|
||||
|
||||
// Initialize storage
|
||||
store, err := storage.New(cfg.DataDir)
|
||||
if err != nil {
|
||||
logging.Logger.WithError(err).Fatal("Failed to initialize storage")
|
||||
}
|
||||
|
||||
// Initialize handlers
|
||||
handlers := api.New(store)
|
||||
|
||||
// Create router
|
||||
mux := router.New(handlers, staticDir)
|
||||
|
||||
// Wrap with logging middleware
|
||||
handler := logging.RequestMiddleware(mux)
|
||||
|
||||
// Start server
|
||||
addr := cfg.Addr()
|
||||
logging.Logger.WithField("addr", addr).Info("Server listening")
|
||||
if err := http.ListenAndServe(addr, handler); err != nil {
|
||||
logging.Logger.WithError(err).Fatal("Server error")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
14
backend/go.mod
Normal file
14
backend/go.mod
Normal file
@@ -0,0 +1,14 @@
|
||||
module github.com/evanreichard/markdown-editor
|
||||
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/cobra v1.8.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
)
|
||||
25
backend/go.sum
Normal file
25
backend/go.sum
Normal file
@@ -0,0 +1,25 @@
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
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
|
||||
}
|
||||
212
backend/test/server_test.go
Normal file
212
backend/test/server_test.go
Normal file
@@ -0,0 +1,212 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/api"
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
"github.com/evanreichard/markdown-editor/internal/router"
|
||||
"github.com/evanreichard/markdown-editor/internal/storage"
|
||||
)
|
||||
|
||||
func TestStaticAssets(t *testing.T) {
|
||||
// Create temporary directories
|
||||
tmpDataDir, err := os.MkdirTemp("", "markdown-data-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp data dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDataDir)
|
||||
|
||||
tmpStaticDir, err := os.MkdirTemp("", "markdown-static-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp static dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpStaticDir)
|
||||
|
||||
// Create a test static file
|
||||
testHTML := "<!DOCTYPE html><html><body>Test</body></html>"
|
||||
err = os.WriteFile(filepath.Join(tmpStaticDir, "index.html"), []byte(testHTML), 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create test file: %v", err)
|
||||
}
|
||||
|
||||
// Initialize storage and handlers
|
||||
store, err := storage.New(tmpDataDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
handlers := api.New(store)
|
||||
|
||||
// Create router with static directory
|
||||
mux := router.New(handlers, tmpStaticDir)
|
||||
|
||||
// Create test server
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
// Test serving index.html
|
||||
resp, err := http.Get(ts.URL + "/")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get index.html: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read response body: %v", err)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(string(body)) != strings.TrimSpace(testHTML) {
|
||||
t.Errorf("Response body mismatch")
|
||||
}
|
||||
|
||||
t.Log("Static assets test passed")
|
||||
}
|
||||
|
||||
func TestAPIRoutes(t *testing.T) {
|
||||
logging.Init()
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "markdown-api-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
store, err := storage.New(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
handlers := api.New(store)
|
||||
mux := router.New(handlers, "")
|
||||
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
// Test GET /api/files (empty)
|
||||
resp, err := http.Get(ts.URL + "/api/files")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get files: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200 for empty list, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test POST /api/files
|
||||
reqBody := `{"name":"test.md","content":"# Test"}`
|
||||
resp, err = http.Post(ts.URL+"/api/files", "application/json", strings.NewReader(reqBody))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Errorf("Expected status 201 for create, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test GET /api/files (with file)
|
||||
resp, err = http.Get(ts.URL + "/api/files")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get files: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200 for list, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test GET /api/files/test.md
|
||||
resp, err = http.Get(ts.URL + "/api/files/test.md")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200 for get, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test PUT /api/files/test.md
|
||||
reqBody = `{"content":"# Updated"}`
|
||||
req, _ := http.NewRequest("PUT", ts.URL+"/api/files/test.md", strings.NewReader(reqBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to update file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("Expected status 200 for update, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test DELETE /api/files/test.md
|
||||
req, _ = http.NewRequest("DELETE", ts.URL+"/api/files/test.md", nil)
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to delete file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Errorf("Expected status 204 for delete, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
t.Log("API routes test passed")
|
||||
}
|
||||
|
||||
func TestErrorResponses(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "markdown-error-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
store, err := storage.New(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
handlers := api.New(store)
|
||||
mux := router.New(handlers, "")
|
||||
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
// Test 404 for non-existent file
|
||||
resp, err := http.Get(ts.URL + "/api/files/nonexistent.md")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Errorf("Expected status 404, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test 400 for invalid name
|
||||
resp, err = http.Get(ts.URL + "/api/files/invalid.txt")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get file: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("Expected status 400, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
t.Log("Error responses test passed")
|
||||
}
|
||||
139
backend/test/storage_test.go
Normal file
139
backend/test/storage_test.go
Normal file
@@ -0,0 +1,139 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/evanreichard/markdown-editor/internal/logging"
|
||||
"github.com/evanreichard/markdown-editor/internal/storage"
|
||||
)
|
||||
|
||||
func init() {
|
||||
logging.Init()
|
||||
}
|
||||
|
||||
func TestStorageCRUD(t *testing.T) {
|
||||
// Create temporary directory
|
||||
tmpDir, err := os.MkdirTemp("", "markdown-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Initialize storage
|
||||
s, err := storage.New(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
// Test Create
|
||||
file, err := s.Create("test.md", "# Test\n\nHello, World!")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create file: %v", err)
|
||||
}
|
||||
if file.Name != "test.md" {
|
||||
t.Errorf("Expected name 'test.md', got '%s'", file.Name)
|
||||
}
|
||||
if file.Content != "# Test\n\nHello, World!" {
|
||||
t.Errorf("Content mismatch")
|
||||
}
|
||||
|
||||
// Test Get
|
||||
retrieved, err := s.Get("test.md")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get file: %v", err)
|
||||
}
|
||||
if retrieved.Name != "test.md" {
|
||||
t.Errorf("Expected name 'test.md', got '%s'", retrieved.Name)
|
||||
}
|
||||
|
||||
// Test Update
|
||||
updated, err := s.Update("test.md", "# Updated\n\nNew content")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to update file: %v", err)
|
||||
}
|
||||
if updated.Content != "# Updated\n\nNew content" {
|
||||
t.Errorf("Update failed, content mismatch")
|
||||
}
|
||||
|
||||
// Test List
|
||||
files, err := s.List()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list files: %v", err)
|
||||
}
|
||||
if len(files) != 1 {
|
||||
t.Errorf("Expected 1 file, got %d", len(files))
|
||||
}
|
||||
|
||||
// Test Delete
|
||||
err = s.Delete("test.md")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to delete file: %v", err)
|
||||
}
|
||||
|
||||
files, err = s.List()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list after delete: %v", err)
|
||||
}
|
||||
if len(files) != 0 {
|
||||
t.Errorf("Expected 0 files after delete, got %d", len(files))
|
||||
}
|
||||
|
||||
// Test Get after delete (should fail)
|
||||
_, err = s.Get("test.md")
|
||||
if err != storage.ErrFileNotFound {
|
||||
t.Errorf("Expected ErrFileNotFound, got %v", err)
|
||||
}
|
||||
|
||||
t.Log("CRUD round-trip test passed")
|
||||
}
|
||||
|
||||
func TestStorageValidation(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "markdown-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
s, err := storage.New(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
// Test invalid names
|
||||
invalidNames := []string{"", "../test.md", "test.txt", "folder/test.md", "test.MD"}
|
||||
for _, name := range invalidNames {
|
||||
_, err := s.Create(name, "content")
|
||||
if err != storage.ErrInvalidName {
|
||||
t.Errorf("Expected ErrInvalidName for '%s', got %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Log("Validation test passed")
|
||||
}
|
||||
|
||||
func TestStorageDuplicateCreate(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "markdown-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
s, err := storage.New(tmpDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
_, err = s.Create("dup.md", "content")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create first file: %v", err)
|
||||
}
|
||||
|
||||
// Try to create duplicate
|
||||
_, err = s.Create("dup.md", "content 2")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error when creating duplicate file")
|
||||
}
|
||||
|
||||
t.Log("Duplicate create test passed")
|
||||
}
|
||||
Reference in New Issue
Block a user