all repos — flounder @ f538215f8cceaf1c7337329ad4aa3b79977042c2

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		Host      string
24		SiteTitle string
25		Files     []*File
26		Users     []string
27	}{
28		Host:      c.Host,
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	// is this necc?
61	server.GetCertificate = func(hostname string, store *gmi.CertificateStore) *tls.Certificate {
62		cert, err := tls.LoadX509KeyPair(c.TLSCertFile, c.TLSKeyFile)
63		if err != nil {
64			log.Fatal("Invalid TLS cert")
65		}
66		return &cert
67	}
68
69	// replace with wildcard cert
70	hostname := strings.SplitN(c.Host, ":", 1)[0]
71	server.HandleFunc(hostname, gmiIndex)
72	server.HandleFunc("*."+hostname, gmiPage)
73
74	server.ListenAndServe()
75}