summaryrefslogtreecommitdiff
path: root/examples/fileserver/main.go
blob: e70974f02809a319e9cb7a7393ddba8fe47d8fe2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main

import (
	"context"
	"log"
	"os"

	"tildegit.org/tjp/gus"
	"tildegit.org/tjp/gus/contrib/fs"
	"tildegit.org/tjp/gus/gemini"
	"tildegit.org/tjp/gus/logging"
)

func main() {
	// Get TLS files from the environment
	certfile, keyfile := envConfig()

	// build a TLS configuration suitable for gemini
	tlsconf, err := gemini.FileTLS(certfile, keyfile)
	if err != nil {
		log.Fatal(err)
	}

	// build the request handler
	fileSystem := os.DirFS(".")
	// Fallthrough tries each handler in succession until it gets something other than "51 Not Found"
	handler := gus.FallthroughHandler(
		// first see if they're fetching a directory and we have <dir>/index.gmi
		fs.DirectoryDefault(fileSystem, "index.gmi"),
		// next (still if they requested a directory) build a directory listing response
		fs.DirectoryListing(fileSystem, nil),
		// finally, try to find a file at the request path and respond with that
		fs.FileHandler(fileSystem),
	)

	_, infoLog, _, errLog := logging.DefaultLoggers()

	// add request logging to stdout
	handler = logging.LogRequests(infoLog)(handler)

	// run the server
	server, err := gemini.NewServer(context.Background(), errLog, tlsconf, "tcp4", ":1965", handler)
	if err != nil {
		log.Fatal(err)
	}
	server.Serve()
}

func envConfig() (string, string) {
	certfile, ok := os.LookupEnv("SERVER_CERTIFICATE")
	if !ok {
		log.Fatal("missing SERVER_CERTIFICATE environment variable")
	}

	keyfile, ok := os.LookupEnv("SERVER_PRIVATEKEY")
	if !ok {
		log.Fatal("missing SERVER_PRIVATEKEY environment variable")
	}

	return certfile, keyfile
}