all repos — flounder @ 7bf10b1a0e72bf7bfa0a249b84c3233eff6a5f7a

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, _ := getIndexFiles()
23	users, _ := getUsers()
24	data := struct {
25		Host      string
26		SiteTitle string
27		Files     []*File
28		Users     []string
29	}{
30		Host:      c.Host,
31		SiteTitle: c.SiteTitle,
32		Files:     files,
33		Users:     users,
34	}
35	t.Execute(w, data)
36}
37
38func gmiPage(w *gmi.ResponseWriter, r *gmi.Request) {
39	userName := strings.Split(r.URL.Host, ".")[0]
40	fileName := filepath.Clean(r.URL.Path)
41	if fileName == "/" {
42		fileName = "index.gmi"
43	}
44	filePath := path.Join(c.FilesDirectory, userName, fileName)
45	log.Println("Request for gemini file at", filePath)
46	data, err := ioutil.ReadFile(filePath)
47
48	if err != nil {
49		w.WriteHeader(51, "Not Found")
50		return
51	}
52	ext := filepath.Ext(filePath)
53	mimetype := mime.TypeByExtension(ext)
54	w.SetMimetype(mimetype)
55	_, err = w.Write(data)
56	if err != nil {
57		log.Fatal(err)
58		w.WriteHeader(40, "Internal server error")
59		return
60	}
61}
62
63func runGeminiServer() {
64	log.Println("Starting gemini server")
65	var server gmi.Server
66
67	hostname := strings.SplitN(c.Host, ":", 2)[0]
68	// is this necc?
69	server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
70		cert, err := store.Lookup(hostname)
71		if err != nil {
72			cert, err := tls.LoadX509KeyPair(c.TLSCertFile, c.TLSKeyFile)
73			if err != nil {
74				log.Fatal("Invalid TLS cert")
75			}
76			store.Add(hostname, cert)
77			return &cert
78		}
79		return cert
80	}
81
82	var mux gmi.ServeMux
83	// replace with wildcard cert
84	mux.HandleFunc("/", gmiIndex)
85
86	var wildcardMux gmi.ServeMux
87	wildcardMux.HandleFunc("/", gmiPage)
88	server.Register(hostname, &mux)
89	server.Register("*."+hostname, &wildcardMux)
90
91	err := server.ListenAndServe()
92	if err != nil {
93		log.Fatal(err)
94	}
95}