all repos — flounder @ 35f0a3f55d49b0043cb33279ea6867ec32362e22

A small site builder for the Gemini protocol

http.go (view raw)

 1package main
 2
 3import (
 4	"fmt"
 5	"html/template"
 6	"log"
 7	"net/http"
 8)
 9
10var t *template.Template
11
12type IndexHandler struct {
13	Domain    string
14	SiteTitle string
15}
16
17// TODO somewhat better error handling
18const InternalServerError = "500: Internal Server Error"
19
20func renderError(w http.ResponseWriter, errorMsg string) { // TODO think about pointers
21	data := struct{ ErrorMsg string }{errorMsg}
22	err := t.ExecuteTemplate(w, "error.html", data)
23	if err != nil { // shouldn't happen probably
24		fmt.Fprintf(w, errorMsg)
25	}
26}
27
28func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
29	indexFiles, err := getIndexFiles()
30	if err != nil {
31		log.Println(err)
32		w.WriteHeader(http.StatusInternalServerError)
33		renderError(w, InternalServerError)
34		return
35	}
36	allUsers, err := getUsers()
37	if err != nil {
38		w.WriteHeader(http.StatusInternalServerError)
39		renderError(w, InternalServerError)
40		return
41	}
42	data := struct {
43		Domain    string
44		PageTitle string
45		Files     []*File
46		Users     []string
47	}{h.Domain, h.SiteTitle, indexFiles, allUsers}
48	err = t.ExecuteTemplate(w, "index.html", data)
49	if err != nil {
50		w.WriteHeader(http.StatusInternalServerError)
51		renderError(w, InternalServerError)
52		return
53	}
54
55}
56
57func editFileHandler(w http.ResponseWriter, r *http.Request) {
58	// get vs post
59	// read file content
60	authUser := "alex"
61	files, _ := getUserFiles(authUser)
62	for _, file := range files {
63		fmt.Fprintf(w, "%s\n", file.Name)
64	}
65}
66
67func mySiteHandler(w http.ResponseWriter, r *http.Request) {
68	authUser := "alex"
69	files, _ := getUserFiles(authUser)
70	for _, file := range files {
71		fmt.Fprintf(w, "%s\n", file.Name)
72	}
73}
74
75func runHTTPServer(config *Config) {
76	var err error
77	t, err = template.ParseGlob("./templates/*.html") // TODO make template dir configruable
78	if err != nil {
79		log.Fatal(err)
80	}
81	http.Handle("/", &IndexHandler{config.RootDomain, config.SiteTitle})
82	http.HandleFunc("/my_site", mySiteHandler)
83	http.HandleFunc("/edit/", editFileHandler)
84	// http.HandleFunc("/delete/", deleteFileHandler)
85	// login+register functions
86	log.Fatal(http.ListenAndServe(":8080", nil))
87}