all repos — flounder @ 60827dbbdafd978ba7aab4dfeaf136b77a8bba43

A small site builder for the Gemini protocol

gemini.go (view raw)

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