all repos — flounder @ 7dff255849f753cf7b0d73de584f3bb6cb6f1645

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