summaryrefslogtreecommitdiff
path: root/cmd/home/main.go
blob: 68542995aa196b244aecb1c626ff5d14fc06c41a (plain)
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
package main

import (
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"git.sr.ht/~a73x/home/pages"
	"github.com/fsnotify/fsnotify"
	"go.uber.org/zap"
)

func Build(directory string) error {
	pages, err := pages.Collect(directory)
	if err != nil {
		return err
	}

	var errs []error
	for _, page := range pages {
		fmt.Println("building", page.Path)
		err = writeFile(path.Join("public", page.Path), []byte(page.Content))
		if err != nil {
			errs = append(errs, err)
		}
	}

	if errs != nil {
		return errors.Join(errs...)
	}

	return nil
}

func Serve() error {
	logger, err := zap.NewProduction()
	if err != nil {
		return err
	}

	loggingMiddleware := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			next.ServeHTTP(w, r)
			logger.Info("request received",
				zap.String("url", r.URL.Path),
				zap.String("method", r.Method),
				zap.Duration("duration", time.Since(start)),
				zap.String("user-agent", r.UserAgent()),
			)
		})
	}

	mux := http.NewServeMux()

	mux.HandleFunc("GET /", serveFile)

	server := http.Server{
		Addr:    ":8080",
		Handler: loggingMiddleware(mux),
	}

	return server.ListenAndServe()
}

func serveFile(w http.ResponseWriter, r *http.Request) {
	fsPath := strings.TrimRight(r.URL.Path, "/")

	if fsPath == "" {
		fsPath = "index"
	}

	if ext := filepath.Ext(fsPath); ext == "" {
		fsPath += ".html"
	}

	http.ServeFile(w, r, path.Join("public", fsPath))
}

func watchDir(watchDir string) error {
	// Directory to watch

	// Ensure the directory exists
	if _, err := os.Stat(watchDir); os.IsNotExist(err) {
		return err
	}

	// Create a new watcher
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}

	// Start a goroutine to process events
	go func() {
		defer watcher.Close()

		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				log.Printf("Event: %s", event)

				// Trigger a command when a change is detected
				if event.Op&fsnotify.Write == fsnotify.Write ||
					event.Op&fsnotify.Create == fsnotify.Create ||
					event.Op&fsnotify.Remove == fsnotify.Remove {
					err := Build(watchDir)
					if err != nil {
						fmt.Println(err)
					} else {
						fmt.Println("built")
					}

				}

			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				log.Printf("Error: %v", err)
			}
		}
	}()

	// Add the directory to the watcher
	err = filepath.Walk(watchDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			log.Printf("Watching directory: %s", path)
			return watcher.Add(path)
		}
		return nil
	})

	if err != nil {
		return err
	}

	return nil
}
func Run() error {
	contentDir := "content"
	actualPath, err := filepath.EvalSymlinks(contentDir)
	if err != nil {
		return err
	}

	if err := Build(actualPath); err != nil {
		return err
	}

	// watcher
	if err := watchDir(actualPath); err != nil {
		return err
	}

	if err := Serve(); err != nil {
		return err
	}

	return nil
}

func writeFile(name string, contents []byte) error {
	folders := path.Dir(name)
	_, err := os.Stat(folders)
	if os.IsNotExist(err) {
		if err := os.MkdirAll(folders, 0744); err != nil {
			return fmt.Errorf("failed to mkdir %s\n%w", folders, err)
		}
	} else if err != nil {
		return fmt.Errorf("failed to stat folder %s\n%w", folders, err)
	}

	err = os.WriteFile(name, contents, 0666)
	if err != nil {
		return fmt.Errorf("failed to write file %s\n%w", name, err)
	}

	return nil
}

func main() {
	if err := Run(); err != nil {
		log.Panic(err)
	}
}