small pixel drawing of a pufferfish gore

main.go

package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"

	"j3s.sh/gore/internal/assets"
)

func main() {
	var services []*service
	s1 := newService("/home/j3s/code/gore/builddir/git.j3s.sh/vore@v0.0.0-20240814184024-9d6fb2a0444f/vore")
	services = append(services, s1)

	if err := SuperviseServices(services); err != nil {
		log.Fatal(err)
	}

	// this is for ensuring services terminate when ^C kills gore
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	go func() {
		<-ctx.Done()
		log.Println("Received shutdown signal…")
		// arbitrarily select 90 seconds for service shutdown
		// TODO: make this configurable?
		killSupervisedServices(90 * time.Second)
		os.Exit(0)
	}()

	// routes
	http.HandleFunc("GET /", indexHandler)
	http.HandleFunc("GET /status", statusHandler)
	http.HandleFunc("GET /log", logHandler)
	http.Handle("GET /assets/", http.StripPrefix("/assets/", http.FileServer(http.FS(assets.Assets))))
	http.HandleFunc("POST /add", addHandler)

	log.Println("listening on http://localhost:6043...")
	log.Fatal(http.ListenAndServe(":6043", nil))
}

func SuperviseServices(services []*service) error {
	unwrapped := make([]*service, len(services))
	for idx, svc := range services {
		unwrapped[idx] = svc
	}

	superviseServices(unwrapped)

	return nil
}

func newService(path string) *service {
	s := &service{
		cmd:     exec.Command(path),
		stopped: false,
	}

	s.state = NewProcessState()

	tag := filepath.Base(s.Cmd().Path)
	s.Stdout = newLogWriter(tag)
	s.Stderr = newLogWriter(tag)

	return s
}