all repos — flounder @ 375e32af23a03e8d06704af706a817cf5beb5129

A small site builder for the Gemini protocol

gemini.go (view raw)

 1package main
 2
 3import (
 4	"crypto/tls"
 5	"strings"
 6	// "fmt"
 7	gmi "git.sr.ht/~adnano/go-gemini"
 8	"io/ioutil"
 9	"log"
10	"path"
11	"path/filepath"
12	"text/template"
13)
14
15func gmiIndex(w *gmi.ResponseWriter, r *gmi.Request) {
16	log.Println("Index request")
17	t, err := template.ParseFiles("templates/index.gmi")
18	if err != nil {
19		log.Fatal(err)
20	}
21	files, _ := getIndexFiles()
22	users, _ := getUsers()
23	data := struct {
24		Host      string
25		SiteTitle string
26		Files     []*File
27		Users     []string
28	}{
29		Host:      c.Host,
30		SiteTitle: c.SiteTitle,
31		Files:     files,
32		Users:     users,
33	}
34	t.Execute(w, data)
35}
36
37func gmiPage(w *gmi.ResponseWriter, r *gmi.Request) {
38	userName := strings.Split(r.URL.Host, ".")[0]
39	fileName := filepath.Clean(r.URL.Path)
40	if fileName == "/" {
41		fileName = "index.gmi"
42	}
43	filePath := path.Join(c.FilesDirectory, userName, fileName)
44	log.Println("Request for gemini file at", filePath)
45	data, err := ioutil.ReadFile(filePath)
46	// serve file?
47	// TODO write mimetype
48	if err != nil {
49		// TODO return 404 equivalent
50		log.Fatal(err)
51	}
52	_, err = w.Write(data)
53	if err != nil {
54		// return internal server error
55		log.Fatal(err)
56	}
57}
58
59func runGeminiServer() {
60	log.Println("Starting gemini server")
61	var server gmi.Server
62
63	hostname := strings.SplitN(c.Host, ":", 2)[0]
64	// is this necc?
65	server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
66		cert, err := store.Lookup(hostname)
67		if err != nil {
68			cert, err := tls.LoadX509KeyPair(c.TLSCertFile, c.TLSKeyFile)
69			if err != nil {
70				log.Fatal("Invalid TLS cert")
71			}
72			store.Add(hostname, cert)
73			return &cert
74		}
75		return cert
76	}
77
78	var mux gmi.ServeMux
79	// replace with wildcard cert
80	mux.HandleFunc("/", gmiIndex)
81
82	var wildcardMux gmi.ServeMux
83	wildcardMux.HandleFunc("/", gmiPage)
84	server.Register(hostname, &mux)
85	server.Register("*."+hostname, &wildcardMux)
86
87	err := server.ListenAndServe()
88	if err != nil {
89		log.Fatal(err)
90	}
91}