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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
|
package main
import (
"encoding/json"
"fmt"
"image"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
_ "markdown-editor/docs"
"github.com/disintegration/imaging"
"github.com/gosimple/slug"
httpSwagger "github.com/swaggo/http-swagger" // swagger UI handler
_ "github.com/swaggo/swag" // swagger embed files
)
var config Config
func main() {
// Load configuration
loadConfig()
// Serve static files from the "static" directory
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
// API endpoints
http.HandleFunc("/api/config", handleConfig)
http.HandleFunc("/api/save", handleSave)
http.HandleFunc("/api/load", handleLoad)
http.HandleFunc("/api/list", handleList)
http.HandleFunc("/api/media-list", handleMediaList)
http.HandleFunc("/api/process-media", handleProcessMedia)
http.HandleFunc("/api/create-post", handleCreatePost)
http.HandleFunc("/api/tags", handleGetTags)
http.HandleFunc("/api/categories", handleGetCategories)
http.HandleFunc("/api/delete-media", handleDeleteMedia)
http.HandleFunc("/api/upload-media", handleUploadMediaFolder)
// Updated Swagger handler
http.Handle("/swagger/", httpSwagger.Handler(
httpSwagger.URL("/docs/swagger.json"), // The url pointing to API definition
httpSwagger.DeepLinking(true),
httpSwagger.DocExpansion("none"),
httpSwagger.DomID("swagger-ui"),
))
// Determine the address to listen on
addr := fmt.Sprintf(":%d", config.Server.Port)
// Show URL on start if configured
if config.Server.ShowURLOnStart {
log.Printf("Server starting on http://localhost%s", addr)
log.Printf("Swagger UI available at http://localhost%s/swagger/index.html", addr)
} else {
log.Printf("Server starting on port %d", config.Server.Port)
}
// Start the server
log.Fatal(http.ListenAndServe(addr, nil))
}
func loadConfig() {
file, err := ioutil.ReadFile("config.json")
if err != nil {
log.Fatal("Error reading config file:", err)
}
err = json.Unmarshal(file, &config)
if err != nil {
log.Fatal("Error parsing config file:", err)
}
// Set default values if not specified
if config.Server.Port == 0 {
config.Server.Port = 8080
}
if config.Server.GermanFolder == "" {
config.Server.GermanFolder = "../content/de/blog"
}
if config.Server.EnglishFolder == "" {
config.Server.EnglishFolder = "../content/en/blog"
}
// Convert relative paths to absolute paths
absGermanFolder, err := filepath.Abs(config.Server.GermanFolder)
if err != nil {
log.Fatalf("Error converting relative path to absolute path for German folder: %v", err)
}
config.Server.GermanFolder = absGermanFolder
absEnglishFolder, err := filepath.Abs(config.Server.EnglishFolder)
if err != nil {
log.Fatalf("Error converting relative path to absolute path for English folder: %v", err)
}
config.Server.EnglishFolder = absEnglishFolder
}
func handleConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(config)
}
func handleSave(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
content, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
fullPath := getFullPath(filename)
err = ioutil.WriteFile(fullPath, content, 0644)
if err != nil {
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func handleLoad(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
fullPath := getFullPath(filename)
content, err := ioutil.ReadFile(fullPath)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, "File not found", http.StatusNotFound)
} else {
http.Error(w, "Error reading file", http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(content)
}
func handleList(w http.ResponseWriter, r *http.Request) {
files := make(map[string][]string)
germanFiles, err := listFiles(config.Server.GermanFolder)
if err != nil {
http.Error(w, "Error reading German directory", http.StatusInternalServerError)
return
}
files["de"] = germanFiles
englishFiles, err := listFiles(config.Server.EnglishFolder)
if err != nil {
http.Error(w, "Error reading English directory", http.StatusInternalServerError)
return
}
files["en"] = englishFiles
files["en"] = englishFiles
w.Header().Set("Content-Type", "application/json")
lang := r.URL.Query().Get("lang")
switch lang {
case "de":
json.NewEncoder(w).Encode(germanFiles)
case "en":
json.NewEncoder(w).Encode(englishFiles)
default:
json.NewEncoder(w).Encode(files)
}
w.Header().Set("Content-Type", "application/json")
}
func handleMediaList(w http.ResponseWriter, r *http.Request) {
files, err := ioutil.ReadDir(config.Server.MediaFolder)
if err != nil {
http.Error(w, "Error reading media directory", http.StatusInternalServerError)
return
}
var mediaFiles []string
for _, file := range files {
if !file.IsDir() {
mediaFiles = append(mediaFiles, file.Name())
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(mediaFiles)
}
func handleProcessMedia(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var request struct {
File string `json:"file"`
NewName string `json:"newName"`
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
newFileName, err := processMediaFile(request)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response := struct {
Filename string `json:"filename"`
}{
Filename: newFileName,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func handleCreatePost(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var request NewPostRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate required fields
if request.Title == "" || request.Date == "" {
http.Error(w, "Title and date are required", http.StatusBadRequest)
return
}
// Create filename from title
filename := createSlug(request.Title) + ".md"
if request.Thumbnail.LocalFile != "" && request.Thumbnail.URL == "" {
if request.Slug == "" {
request.Slug = slug.Make(request.Title)
}
// Create a variable of the struct type
var reqMediaFile struct {
File string `json:"file"`
NewName string `json:"newName"`
}
reqMediaFile.File = request.Thumbnail.LocalFile
reqMediaFile.NewName = request.Slug
// Log the processing of the media file
log.Printf("Processing media file: %s\n", request.Thumbnail.LocalFile)
newFileName, err := processMediaFile(reqMediaFile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Log the result of the media file processing
log.Printf("Processed media file: %s -> %s\n", request.Thumbnail.LocalFile, newFileName)
request.Thumbnail.URL = "/img/blog/" + newFileName
}
// Determine the target folder based on language
var targetFolder string
switch request.Language {
case "de":
targetFolder = config.Server.GermanFolder
case "en":
targetFolder = config.Server.EnglishFolder
default:
http.Error(w, "Invalid language", http.StatusBadRequest)
return
}
// Generate markdown content
content := generateMarkdownContent(request)
// Save the file
fullPath := filepath.Join(targetFolder, filename)
if err := ioutil.WriteFile(fullPath, []byte(content), 0644); err != nil {
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
// Update tags and categories in config
updateTagsAndCategories(request.Tags, request.Categories)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"filename": filename})
}
func handleGetTags(w http.ResponseWriter, r *http.Request) {
tags, err := getAllTags()
if err != nil {
http.Error(w, "Error reading tags", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(tags)
}
func handleGetCategories(w http.ResponseWriter, r *http.Request) {
categories, err := getAllCategories()
if err != nil {
http.Error(w, "Error reading categories", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(categories)
}
func createSlug(title string) string {
// Convert to lowercase and replace spaces with hyphens
slug := strings.ToLower(title)
slug = strings.ReplaceAll(slug, " ", "-")
// Remove special characters
slug = regexp.MustCompile(`[^a-z0-9-]`).ReplaceAllString(slug, "")
return slug
}
func generateMarkdownContent(post NewPostRequest) string {
var sb strings.Builder
sb.WriteString("---\n")
sb.WriteString(fmt.Sprintf("title: '%s'\n", post.Title))
if post.Slug == "" {
post.Slug = slug.Make(post.Title)
}
sb.WriteString(fmt.Sprintf("slug: %s\n", post.Slug))
if post.Description != "" {
sb.WriteString(fmt.Sprintf("description: '%s'\n", post.Description))
}
// Convert date string to time.Time
date, err := time.Parse("2024-11-06T13:53", post.Date)
if err != nil {
log.Printf("Error parsing date: %v", err)
date = time.Now()
}
// Convert date to UTC
utcDate := date.UTC()
sb.WriteString(fmt.Sprintf("date: %s\n", utcDate.Format(time.RFC3339)))
if len(post.Tags) > 0 {
tags, _ := json.Marshal(post.Tags)
sb.WriteString(fmt.Sprintf("tags: %s\n", strings.ReplaceAll(string(tags), "\"", "")))
}
if len(post.Categories) > 0 {
categories, _ := json.Marshal(post.Categories)
sb.WriteString(fmt.Sprintf("categories: %s\n", strings.ReplaceAll(string(categories), "\"", "")))
}
if post.Thumbnail.URL != "" {
sb.WriteString("thumbnail:\n")
sb.WriteString(fmt.Sprintf(" url: %s\n", post.Thumbnail.URL))
if post.Thumbnail.Author != "" {
sb.WriteString(fmt.Sprintf(" author: %s\n", post.Thumbnail.Author))
}
if post.Thumbnail.AuthorURL != "" {
sb.WriteString(fmt.Sprintf(" authorUrl: %s\n", post.Thumbnail.AuthorURL))
}
if post.Thumbnail.Origin != "" {
sb.WriteString(fmt.Sprintf(" origin: %s\n", post.Thumbnail.Origin))
}
}
sb.WriteString("draft: true\n")
sb.WriteString("---\n")
return sb.String()
}
// getAllTags reads and returns all tags from the tags data file
func getAllTags() ([]Tag, error) {
// Read tags from a JSON file
file, err := ioutil.ReadFile("data/tags.json")
if err != nil {
if os.IsNotExist(err) {
// Return empty array if file doesn't exist
return []Tag{}, nil
}
return nil, err
}
var tagsData TagsData
err = json.Unmarshal(file, &tagsData)
if err != nil {
return nil, err
}
return tagsData.Tags, nil
}
// getAllCategories reads and returns all categories from the categories data file
func getAllCategories() ([]Category, error) {
// Read categories from a JSON file
file, err := ioutil.ReadFile("data/categories.json")
if err != nil {
if os.IsNotExist(err) {
// Return empty array if file doesn't exist
return []Category{}, nil
}
return nil, err
}
var categoriesData CategoriesData
err = json.Unmarshal(file, &categoriesData)
if err != nil {
return nil, err
}
return categoriesData.Categories, nil
}
// updateTagsAndCategories updates the tags and categories data files with new entries
func updateTagsAndCategories(newTags []string, newCategories []string) error {
// Update tags
if err := updateTags(newTags); err != nil {
return err
}
// Update categories
if err := updateCategories(newCategories); err != nil {
return err
}
return nil
}
// updateTags updates the tags data file with new tags
func updateTags(newTags []string) error {
existingTags, err := getAllTags()
if err != nil {
return err
}
// Create a map for existing tags for easy lookup
tagMap := make(map[string]*Tag)
for i := range existingTags {
tagMap[existingTags[i].Name] = &existingTags[i]
}
// Update counts for existing tags and add new ones
for _, newTag := range newTags {
if tag, exists := tagMap[newTag]; exists {
tag.Count++
} else {
existingTags = append(existingTags, Tag{
Name: newTag,
Count: 1,
})
}
}
// Create data directory if it doesn't exist
if err := os.MkdirAll("data", 0755); err != nil {
return err
}
// Save updated tags to file
tagsData := TagsData{Tags: existingTags}
jsonData, err := json.MarshalIndent(tagsData, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile("data/tags.json", jsonData, 0644)
}
// updateCategories updates the categories data file with new categories
func updateCategories(newCategories []string) error {
existingCategories, err := getAllCategories()
if err != nil {
return err
}
// Create a map for existing categories for easy lookup
categoryMap := make(map[string]*Category)
for i := range existingCategories {
categoryMap[existingCategories[i].Name] = &existingCategories[i]
}
// Update counts for existing categories and add new ones
for _, newCategory := range newCategories {
if category, exists := categoryMap[newCategory]; exists {
category.Count++
} else {
existingCategories = append(existingCategories, Category{
Name: newCategory,
Count: 1,
})
}
}
// Create data directory if it doesn't exist
if err := os.MkdirAll("data", 0755); err != nil {
return err
}
// Save updated categories to file
categoriesData := CategoriesData{Categories: existingCategories}
jsonData, err := json.MarshalIndent(categoriesData, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile("data/categories.json", jsonData, 0644)
}
func processMediaFile(request struct {
File string `json:"file"`
NewName string `json:"newName"`
}) (string, error) {
sourceFile := filepath.Join(config.Server.MediaFolder, request.File)
ext := filepath.Ext(request.File)
newFileName := request.NewName + ext
destFile := filepath.Join(config.Server.AssetFolder, newFileName)
// Open the source image
src, err := imaging.Open(sourceFile)
if err != nil {
return "", fmt.Errorf("error opening source image: %w", err)
}
// Get the dimensions of the source image
srcWidth := src.Bounds().Dx()
srcHeight := src.Bounds().Dy()
// Calculate the new height to maintain the aspect ratio
newHeight := (config.Server.ImageResize.MaxWidth * srcHeight) / srcWidth
// Resize the image
var resized image.Image
if config.Server.ImageResize.Method == "fit" {
resized = imaging.Fit(src, config.Server.ImageResize.MaxWidth, newHeight, imaging.Lanczos)
} else {
resized = imaging.Fill(src, config.Server.ImageResize.MaxWidth, newHeight, imaging.Center, imaging.Lanczos)
}
// Save the resized image
err = imaging.Save(resized, destFile)
if err != nil {
return "", fmt.Errorf("error saving resized image: %w", err)
}
// Create and save thumbnail
var thumbnail image.Image
if config.Server.ThumbnailResize.Method == "fit" {
thumbnail = imaging.Fit(src, config.Server.ThumbnailResize.MaxWidth, newHeight, imaging.Lanczos)
} else {
thumbnail = imaging.Fill(src, config.Server.ThumbnailResize.MaxWidth, newHeight, imaging.Center, imaging.Lanczos)
}
thumbnailFile := filepath.Join(config.Server.AssetFolder, "thumb_"+newFileName)
err = imaging.Save(thumbnail, thumbnailFile)
if err != nil {
return "", fmt.Errorf("error saving thumbnail: %w", err)
}
return newFileName, nil
}
func handleUploadMediaFolder(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the multipart form data with a 32MB limit
err := r.ParseMultipartForm(32 << 20)
if err != nil {
http.Error(w, "Error parsing form data", http.StatusBadRequest)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving file", http.StatusBadRequest)
return
}
defer file.Close()
// Generate a unique filename
ext := filepath.Ext(header.Filename)
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
// Create the full path for the new file
fullPath := filepath.Join(config.Server.MediaFolder, filename)
// Create a new file in the media folder
dst, err := os.Create(fullPath)
if err != nil {
http.Error(w, "Error creating file", http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy the uploaded file to the destination
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
// Return the filename in the response
response := struct {
Filename string `json:"filename"`
}{
Filename: filename,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func handleUploadMedia(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the multipart form data with a 32MB limit
err := r.ParseMultipartForm(32 << 20)
if err != nil {
http.Error(w, "Error parsing form data", http.StatusBadRequest)
return
}
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving file", http.StatusBadRequest)
return
}
defer file.Close()
// Generate a unique filename
ext := filepath.Ext(header.Filename)
filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), ext)
// Create the full path for the new file
fullPath := filepath.Join(config.Server.MediaFolder, filename)
// Create a new file in the media folder
dst, err := os.Create(fullPath)
if err != nil {
http.Error(w, "Error creating file", http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy the uploaded file to the destination
_, err = io.Copy(dst, file)
if err != nil {
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
// Return the filename in the response
response := struct {
Filename string `json:"filename"`
}{
Filename: filename,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func handleDeleteMedia(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
filename := r.URL.Query().Get("file")
if filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
// Ensure the filename is safe
if strings.Contains(filename, "..") {
http.Error(w, "Invalid filename", http.StatusBadRequest)
return
}
// Create the full path for the file
fullPath := filepath.Join(config.Server.MediaFolder, filename)
// Check if file exists
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
http.Error(w, "File not found", http.StatusNotFound)
return
}
// Delete the file
err := os.Remove(fullPath)
if err != nil {
http.Error(w, "Error deleting file", http.StatusInternalServerError)
return
}
// Also delete thumbnail if it exists
thumbPath := filepath.Join(config.Server.MediaFolder, "thumb_"+filename)
_ = os.Remove(thumbPath) // Ignore error as thumbnail might not exist
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}
|