all repos — flounder @ 3c696860461d44ec54c7a718b3e5221705c5e2d1

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 InternalServerErrorMsg = "500: Internal Server Error"
19
20func renderError(w http.ResponseWriter, errorMsg string, statusCode int) { // 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		http.Error(w, errorMsg, statusCode)
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		renderError(w, InternalServerErrorMsg, 500)
33		return
34	}
35	allUsers, err := getUsers()
36	if err != nil {
37		log.Println(err)
38		renderError(w, InternalServerErrorMsg, 500)
39		return
40	}
41	data := struct {
42		Domain    string
43		PageTitle string
44		Files     []*File
45		Users     []string
46	}{h.Domain, h.SiteTitle, indexFiles, allUsers}
47	err = t.ExecuteTemplate(w, "index.html", data)
48	if err != nil {
49		log.Println(err)
50		renderError(w, InternalServerErrorMsg, 500)
51		return
52	}
53
54}
55
56func editFileHandler(w http.ResponseWriter, r *http.Request) {
57	// get vs post
58	// read file content
59	authUser := "alex"
60	files, _ := getUserFiles(authUser)
61	for _, file := range files {
62		fmt.Fprintf(w, "%s\n", file.Name)
63	}
64}
65
66func mySiteHandler(w http.ResponseWriter, r *http.Request) {
67	authUser := "alex"
68	files, _ := getUserFiles(authUser)
69	for _, file := range files {
70		fmt.Fprintf(w, "%s\n", file.Name)
71	}
72}
73
74func runHTTPServer(config *Config) {
75	var err error
76	t, err = template.ParseGlob("./templates/*.html") // TODO make template dir configruable
77	if err != nil {
78		log.Fatal(err)
79	}
80	http.Handle("/", &IndexHandler{config.RootDomain, config.SiteTitle})
81	http.HandleFunc("/my_site", mySiteHandler)
82	http.HandleFunc("/edit/", editFileHandler)
83	// http.HandleFunc("/delete/", deleteFileHandler)
84	// login+register functions
85	log.Fatal(http.ListenAndServe(":8080", nil))
86}