From ff05d62013906f3086b452bfeda3e0d5b9b7a541 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Mon, 9 Jan 2023 16:40:24 -0700 Subject: Initial commit. some basics: - minimal README - some TODOs - server and request handler framework - contribs: file serving, request logging - server examples - CI setup --- examples/fileserver/main.go | 60 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 examples/fileserver/main.go (limited to 'examples/fileserver/main.go') diff --git a/examples/fileserver/main.go b/examples/fileserver/main.go new file mode 100644 index 0000000..01d22ee --- /dev/null +++ b/examples/fileserver/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "log" + "net" + "os" + + "tildegit.org/tjp/gus/contrib/fs" + guslog "tildegit.org/tjp/gus/contrib/log" + "tildegit.org/tjp/gus/gemini" +) + +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) + } + + // set up the network listen + listener, err := net.Listen("tcp4", ":1965") + 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 := gemini.Fallthrough( + // first see if they're fetching a directory and we have /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), + ) + // add request logging to stdout + handler = guslog.Requests(os.Stdout, nil)(handler) + + // run the server + gemini.NewServer(context.Background(), tlsconf, listener, handler).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 +} -- cgit v1.2.3