summaryrefslogtreecommitdiff
path: root/web/web.go
blob: 487dd8126aaab0db9d6b76839907776b2056d34d (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
package web

import (
	"bytes"
	"fmt"
	"io"
	"io/fs"
	"net/http"
	"path/filepath"
	"strings"
	"text/template"
	"time"

	"git.sr.ht/~a73x/home"
	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/parser"
	"go.abhg.dev/goldmark/frontmatter"
	"go.uber.org/zap"
)

type CommonData struct {
	Posts []PostData
}

type PostData struct {
	Title string
	Path  string
}

func GeneratePosts(mux *http.ServeMux) ([]PostData, error) {
	converter := goldmark.New(
		goldmark.WithExtensions(
			&frontmatter.Extender{},
		))

	t, err := template.ParseFS(home.Content, "templates/layouts/*.html")
	if err != nil {
		return nil, fmt.Errorf("failed to parse layouts: %v", err)
	}

	final := []PostData{}
	posts, err := fs.Glob(home.Content, "posts/*.md")
	if err != nil {
		return nil, fmt.Errorf("failed to glob posts: %v", err)
	}

	for _, post := range posts {
		postName := filepath.Base(post)
		postName = strings.Split(postName, ".")[0] + ".html"

		// parse markdown
		input, err := fs.ReadFile(home.Content, post)
		if err != nil {
			return nil, fmt.Errorf("failed to read post: %v", err)
		}

		var b bytes.Buffer
		ctx := parser.NewContext()
		if err := converter.Convert(input, &b, parser.WithContext(ctx)); err != nil {
			return nil, err
		}

		d := frontmatter.Get(ctx)
		var meta map[string]string
		if err := d.Decode(&meta); err != nil {
			return nil, err
		}

		foo, err := t.ParseFS(home.Content, "templates/post.html")
		if err != nil {
			return nil, fmt.Errorf("failed to parse post template: %v", err)
		}

		content, err := io.ReadAll(&b)
		if err != nil {
			return nil, fmt.Errorf("failed to read post template: %v", err)
		}

		type IPostData struct {
			Title string
			Post  string
		}

		mux.HandleFunc("/posts/"+postName, func(w http.ResponseWriter, r *http.Request) {
			if err := foo.ExecuteTemplate(w, "post.html", IPostData{
				Title: meta["title"],
				Post:  string(content),
			}); err != nil {
				fmt.Println(err)
			}
		})

		final = append(final, PostData{
			Title: meta["title"],
			Path:  "posts/" + postName,
		})
	}

	return final, nil
}

func loadTemplates(mux *http.ServeMux, data any) error {
	tmplFiles, err := fs.ReadDir(home.Content, "templates")
	if err != nil {
		return fmt.Errorf("failed to parse template layouts")
	}

	for _, tmpl := range tmplFiles {
		if tmpl.IsDir() {
			continue
		}

		pt, err := template.ParseFS(home.Content, "templates/"+tmpl.Name(), "templates/layouts/*.html")
		if err != nil {
			return fmt.Errorf("failed to parse template "+tmpl.Name(), err)
		}

		if tmpl.Name() == "index.html" {
			mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
				pt.ExecuteTemplate(w, tmpl.Name(), data)
			})
		} else if tmpl.Name() == "page.html" {
			continue
		} else {
			mux.HandleFunc("/"+tmpl.Name(), func(w http.ResponseWriter, r *http.Request) {
				pt, err := template.ParseFS(home.Content, "templates/"+tmpl.Name(), "templates/layouts/*.html")
				if err != nil {
					fmt.Printf("failed to parse template "+tmpl.Name(), err)
				}
				pt.ExecuteTemplate(w, tmpl.Name(), data)
			})
		}
	}
	return nil
}
func New(logger *zap.Logger) (*http.Server, error) {
	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()
	postData, err := GeneratePosts(mux)
	if err != nil {
		return nil, fmt.Errorf("failed to generate posts: %v", err)
	}

	data := CommonData{
		Posts: postData,
	}

	if err := loadTemplates(mux, data); err != nil {
		return nil, fmt.Errorf("failed to parse templates: %v", err)
	}

	staticFs, err := fs.Sub(home.Content, "public/static")
	if err != nil {
		return nil, fmt.Errorf("failed to setup static handler: %v", err)
	}

	mux.Handle("GET /static", http.FileServer(http.FS(staticFs)))

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

	return &server, nil
}