summaryrefslogtreecommitdiff
path: root/pkg/backend/run.go
blob: 2af47ab2338d55ccc52931c1b4b6c1421b93e82e (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
package backend

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

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

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

	host := getenv("TFSTATED_HOST")
	if host == "" {
		host = "127.0.0.1"
	}
	port := getenv("TFSTATED_PORT")
	if port == "" {
		port = "8080"
	}

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

	return httpServer
}