summaryrefslogtreecommitdiff
path: root/internal/nginx/nginx.go
blob: abdd4c937264dc8313c81f3ed270b157384c78e0 (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 nginx regenerates one vhost file per app and reloads. Skiff never
// touches nginx.conf itself - that just needs one `include skiff.d/*.conf;`
// line added once, by hand, when nginx is first set up.
package nginx

import (
	"context"
	"fmt"
	"io"
	"os"

	"skiff/internal/layout"
	"skiff/internal/sh"
	"skiff/internal/tmpl"
)

// EnsureRoute writes app's vhost file and reloads nginx, but only if the
// rendered config actually changed - most deploys don't touch routing.
func EnsureRoute(ctx context.Context, out io.Writer, cfg layout.Config, app, ip string, port int, serverName string) error {
	rendered, err := tmpl.NginxApp(tmpl.NginxAppData{
		Name:       app,
		IP:         ip,
		Port:       port,
		ServerName: serverName,
	})
	if err != nil {
		return err
	}

	path := cfg.NginxConfPath(app)
	existing, _ := os.ReadFile(path)
	if string(existing) == rendered {
		return nil
	}

	if err := os.WriteFile(path, []byte(rendered), 0644); err != nil {
		return fmt.Errorf("write nginx conf for %s: %w", app, err)
	}
	fmt.Fprintf(out, "==> nginx route changed for %s, reloading\n", app)
	return Reload(ctx, out)
}

func Reload(ctx context.Context, out io.Writer) error {
	return sh.Run(ctx, out, "", "nginx", "-s", "reload")
}