main.go
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
package main import ( "html/template" "log" "net/http" "os" "path/filepath" "strings" "git.j3s.sh/j3s.sh/feed" ) // templateData is a mega-struct that gets // passed to every single template - put whatever // you want in it tbh. // // "data" is a global object that contains arbitrary // data for use in templates. it's useful for it to be // global since it may need to be available in arbitrary // contexts. maybe that sucks. but idfk! type templateData struct { FriendPosts []string } var data templateData // the populate function populates the global "data" variable // with ... data. with which to pass into templates. func (t *templateData) populate() { t.FriendPosts = feed.FetchRecentFriendPosts() } func main() { data.populate() fs := http.FileServer(http.Dir("./static")) http.Handle("/static/", http.StripPrefix("/static/", fs)) http.HandleFunc("/review/", babyHandler) http.HandleFunc("/idea/", babyHandler) http.HandleFunc("/", serveTemplate) log.Println("listening on :4666 tbh") err := http.ListenAndServe(":4666", nil) if err != nil { log.Fatal(err) } } func serveTemplate(w http.ResponseWriter, r *http.Request) { lp := filepath.Join("templates", "layout.html") if r.URL.Path == "/" { r.URL.Path = "index.html" // TODO: add some arbitrary refresh handler for fetchFriendPosts } fp := filepath.Join("templates", filepath.Clean(r.URL.Path)) info, err := os.Stat(fp) if err != nil { if os.IsNotExist(err) { http.NotFound(w, r) return } } if info.IsDir() { http.NotFound(w, r) return } tmpl, err := template.ParseFiles(lp, fp) if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) return } err = tmpl.ExecuteTemplate(w, "layout", data) if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) } } func babyHandler(w http.ResponseWriter, r *http.Request) { lp := filepath.Join("templates", "simple-layout.html") fp := filepath.Join(strings.TrimPrefix(filepath.Clean(r.URL.Path), "/")) info, err := os.Stat(fp) if err != nil { if os.IsNotExist(err) { http.NotFound(w, r) return } } if info.IsDir() { http.NotFound(w, r) return } content, err := os.ReadFile(fp) if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) return } tmpl, err := template.ParseFiles(lp) if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) return } err = tmpl.ExecuteTemplate(w, "simple-layout", string(content)) if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) } }