💾 Archived View for source.community › ckaznocha › cliftons-capsule › raw › main › main.go captured on 2023-04-19 at 23:19:17.

View Raw

More Information

⬅️ Previous capture (2021-12-17)

-=-=-=-=-=-=-

package main

import (
	"context"
	"crypto/tls"
	"embed"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"

	"source.community/ckaznocha/gemini"
)

//go:embed templates
var templateFS embed.FS

func main() {
	logger := log.New(os.Stdout, "[Gemini Capsule] ", log.LstdFlags)

	cert := flag.String("tls_cert", "cert.pem", "path to the tls cert file")
	key := flag.String("tls_key", "key.pem", "path to the tls key file")
	addr := flag.String("listen_addr", ":1965", "address to listen on")
	assets := flag.String("assets", "assets", "path to assets dir")
	flag.Parse()

	logger.Println("Server starting")

	app, err := newApp(logger, os.DirFS(*assets), templateFS)
	if err != nil {
		logger.Fatal(err)
	}

	mux := gemini.NewServeMux()
	mux.HandleFunc("/", app.indexHandler)
	mux.HandleFunc("/gemlog", app.gemlogHandler)

	s := &gemini.Server{
		Handler: mux,
		LogHandler: func(message string, isError bool) {
			if isError {
				logger.Printf("gemini server: %s", message)
			}
		},
		TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
	}

	s.RegisterOnShutdown(func() {
		s.LogHandler("shutting down", false)
	})

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	logger.Println("Server started")

	go func() {
		defer cancel()

		s.LogHandler("starting", false)
		err := s.ListenAndServeTLS(*addr, *cert, *key)
		s.LogHandler(fmt.Sprintf("exited: %s\n", err), true)
	}()

	ctx, stop := signal.NotifyContext(ctx, os.Interrupt)
	defer stop()

	<-ctx.Done()

	fmt.Fprint(logger.Writer(), "\n")

	logger.Println("Shutdown starting")
	defer logger.Println("Shutdown complete")

	if err := s.Shutdown(context.Background()); err != nil {
		logger.Printf("Error during shutdown: %s\n", err)
	}
}