gemini.go (view raw)
1package main
2
3import (
4 "crypto/tls"
5 "strings"
6 // "fmt"
7 gmi "git.sr.ht/~adnano/go-gemini"
8 "log"
9 "path"
10 "path/filepath"
11 "text/template"
12 "time"
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, err := getIndexFiles()
22 users, err := getActiveUserNames()
23 if err != nil {
24 log.Println(err)
25 w.WriteHeader(40, "Internal server error")
26 }
27 data := struct {
28 Host string
29 SiteTitle string
30 Files []*File
31 Users []string
32 }{
33 Host: c.Host,
34 SiteTitle: c.SiteTitle,
35 Files: files,
36 Users: users,
37 }
38 t.Execute(w, data)
39}
40
41func gmiPage(w *gmi.ResponseWriter, r *gmi.Request) {
42 userName := filepath.Clean(strings.Split(r.URL.Host, ".")[0]) // clean probably unnecessary
43 fileName := filepath.Clean(r.URL.Path)
44 if fileName == "/" {
45 fileName = "index.gmi"
46 }
47 log.Println("Request for gemini file", fileName, "for user", userName)
48
49 gmi.ServeFile(w, gmi.Dir(path.Join(c.FilesDirectory, userName)), fileName)
50}
51
52func runGeminiServer() {
53 log.Println("Starting gemini server")
54 var server gmi.Server
55
56 hostname := strings.SplitN(c.Host, ":", 2)[0]
57 // is this necc?
58 server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
59 log.Println("Generating certificate for", hostname)
60 cert, err := gmi.CreateCertificate(gmi.CertificateOptions{
61 DNSNames: []string{hostname},
62 Duration: time.Minute * 43200, // one month
63 })
64 if err == nil {
65 // Write the new certificate to disk
66 err = writeCertificate(path.Join(c.GeminiCertStore, hostname), cert)
67 }
68 return cert, err
69 }
70
71 var mux gmi.ServeMux
72 // replace with wildcard cert
73 mux.HandleFunc("/", gmiIndex)
74
75 var wildcardMux gmi.ServeMux
76 wildcardMux.HandleFunc("/", gmiPage)
77 server.Register(hostname, &mux)
78 server.Register("*."+hostname, &wildcardMux)
79
80 err := server.ListenAndServe()
81 if err != nil {
82 log.Fatal(err)
83 }
84}