summaryrefslogtreecommitdiff
path: root/pkg/webui/run.go
blob: 664b9e521bc9dd5a2b63b623ea517990e4a1f4f3 (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
package webui

import (
	"context"
	"embed"
	"log/slog"
	"net"
	"net/http"

	"git.adyxax.org/adyxax/tfstated/pkg/database"
	"git.adyxax.org/adyxax/tfstated/pkg/middlewares/logger"
)

//go:embed html/*
var htmlFS embed.FS

//go:embed static/*
var staticFS embed.FS

func Run(
	ctx context.Context,
	db *database.DB,
	getenv func(string) string,
) *http.Server {
	mux := http.NewServeMux()
	addRoutes(
		mux,
		db,
	)

	host := getenv("TFSTATED_WEBUI_HOST")
	if host == "" {
		host = "127.0.0.1"
	}
	port := getenv("TFSTATED_WEBUI_PORT")
	if port == "" {
		port = "8081"
	}

	httpServer := &http.Server{
		Addr:    net.JoinHostPort(host, port),
		Handler: logger.Middleware(mux, false),
	}
	go func() {
		slog.Info("webui http server listening", "address", httpServer.Addr)
		if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			slog.Error("error listening and serving webui http server", "address", httpServer.Addr, "error", err)
		}
	}()

	return httpServer
}