all repos — flounder @ e806ee97af47b96ed240b2c4ff0e20ee99eb4640

A small site builder for the Gemini protocol

gemini.go (view raw)

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