gemini.go (view raw)
1package main
2
3import (
4 "crypto/tls"
5 "crypto/x509/pkix"
6 gmi "git.sr.ht/~adnano/go-gemini"
7 "log"
8 "path"
9 "path/filepath"
10 "strings"
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 } else if strings.HasPrefix(fileName, "/.hidden") {
47 w.WriteStatus(gmi.StatusNotFound)
48 return
49 }
50 log.Println("Request for gemini file", fileName, "for user", userName)
51
52 gmi.ServeFile(w, gmi.Dir(path.Join(c.FilesDirectory, userName)), fileName)
53}
54
55func runGeminiServer() {
56 log.Println("Starting gemini server")
57 var server gmi.Server
58 server.ReadTimeout = 1 * time.Minute
59 server.WriteTimeout = 2 * time.Minute
60
61 hostname := strings.SplitN(c.Host, ":", 2)[0]
62 // is this necc?
63 err := server.Certificates.Load(c.GeminiCertStore)
64 if err != nil {
65 }
66 server.CreateCertificate = func(h string) (tls.Certificate, error) {
67 log.Println("Generating certificate for", h)
68 return gmi.CreateCertificate(gmi.CertificateOptions{
69 Subject: pkix.Name{
70 CommonName: hostname,
71 },
72 DNSNames: []string{h},
73 Duration: time.Hour * 760, // one month
74 })
75 }
76
77 var mux gmi.ServeMux
78 // replace with wildcard cert
79 mux.HandleFunc("/", gmiIndex)
80
81 var wildcardMux gmi.ServeMux
82 wildcardMux.HandleFunc("/", gmiPage)
83 server.Register(hostname, &mux)
84 server.Register("*."+hostname, &wildcardMux)
85
86 err = server.ListenAndServe()
87 if err != nil {
88 log.Fatal(err)
89 }
90}