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