about summary refs log tree commit diff stats
path: root/cmd/server/server.go
blob: cc1821a208dc0f4cf675e304d7060b7240b94b6f (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	cfg "website/internal/config"

	"github.com/ansrivas/fiberprometheus/v2"
	"github.com/ardanlabs/conf/v3"
	"github.com/getsentry/sentry-go"
	"github.com/gofiber/contrib/fibersentry"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cache"
	"github.com/gofiber/fiber/v2/middleware/compress"
	"github.com/gofiber/fiber/v2/middleware/etag"
	"github.com/gofiber/fiber/v2/middleware/filesystem"
	"github.com/gofiber/fiber/v2/middleware/healthcheck"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/fiber/v2/middleware/recover"
	"github.com/gofiber/fiber/v2/middleware/skip"

	"github.com/shengyanli1982/law"
)

type Config struct {
	Production             bool    `conf:"default:false"`
	ListenAddress          string  `conf:"default:localhost"`
	Port                   uint16  `conf:"default:3000,short:p"`
	BaseURL                cfg.URL `conf:"default:http://localhost:3000,short:b"`
	RedirectOtherHostnames bool    `conf:"default:false"`
}

// TODO purge CSS
// TODO HTTP2 https://github.com/dgrr/http2

type Host struct {
	Fiber *fiber.App
}

var Commit string

func main() {
	runtimeConfig := Config{}
	if help, err := conf.Parse("", &runtimeConfig); err != nil {
		if errors.Is(err, conf.ErrHelpWanted) {
			fmt.Println(help)
			os.Exit(1)
		}
		log.Panicf("parsing runtime configuration: %v", err)
	}
	config, err := cfg.GetConfig()
	if err != nil {
		log.Panicf("parsing configuration file: %v", err)
	}

	err = sentry.Init(sentry.ClientOptions{
		Dsn:         os.Getenv("SENTRY_DSN"),
		Release:     os.Getenv("FLY_MACHINE_VERSION"),
		Environment: os.Getenv("ENV"),
	})
	if err != nil {
		log.Panic("could not set up sentry")
	}
	defer sentry.Flush(2 * time.Second)

	metricServer := fiber.New(fiber.Config{
		GETOnly:                  true,
		StrictRouting:            true,
		DisableDefaultDate:       true,
		DisableHeaderNormalizing: true,
		DisableStartupMessage:    true,
		Network:                  fiber.NetworkTCP,
	})
	prometheus := fiberprometheus.New("homestead")
	prometheus.RegisterAt(metricServer, "/metrics")

	hosts := map[string]*Host{}

	internal := fiber.New(fiber.Config{
		GETOnly:       true,
		StrictRouting: true,
	})
	internal.Use(healthcheck.New(healthcheck.Config{}))
	hosts["fly-internal"] = &Host{internal}

	website := fiber.New(fiber.Config{
		EnableTrustedProxyCheck: true,
		TrustedProxies:          []string{"172.16.0.0/16"},
		ProxyHeader:             "Fly-Client-IP",
		GETOnly:                 true,
		ReadTimeout:             5 * time.Minute,
		WriteTimeout:            5 * time.Minute,
		StrictRouting:           true,
		UnescapePath:            true,
	})

	website.Use(prometheus.Middleware)
	website.Use(fibersentry.New(fibersentry.Config{}))
	website.Use(func(c *fiber.Ctx) error {
		for k, v := range config.Extra.Headers {
			c.Set(k, v)
		}
		if c.Secure() {
			c.Set("Strict-Transport-Security", "max-age=31536000; includeSubdomains; preload")
		}
		return c.Next()
	})

	website.Use(compress.New())
	website.Use(cache.New(cache.Config{
		CacheControl:         true,
		Expiration:           24 * time.Hour,
		StoreResponseHeaders: true,
	}))
	// must be after compress to be encoding-independent
	website.Use(etag.New(etag.Config{
		Weak: true,
	}))

	website.Use(recover.New(recover.Config{}))

	prefix := "website/public"
	publicFiles := http.Dir(prefix)
	website.Use("/", filesystem.New(filesystem.Config{
		Root:               publicFiles,
		ContentTypeCharset: "utf-8",
		MaxAge:             int((24 * time.Hour).Seconds()),
	}))
	website.Use(func(c *fiber.Ctx) error {
		c.Status(fiber.StatusNotFound).Type("html", "utf-8")
		content, err := os.Open("website/private/404.html")
		if err != nil {
			c.Type("txt")
			return c.SendString("404 Not Found")
		}
		return c.SendStream(content)
	})
	hosts[runtimeConfig.BaseURL.Host] = &Host{website}

	toplevel := fiber.New(fiber.Config{
		DisableStartupMessage: runtimeConfig.Production,
		ServerHeader:          fmt.Sprintf("website (%s)", Commit),
		Network:               fiber.NetworkTCP,
	})
	toplevel.Get("/health", func(c *fiber.Ctx) error {
		return c.SendStatus(fiber.StatusOK)
	})
	var logWriter io.Writer
	if runtimeConfig.Production {
		logWriter = law.NewWriteAsyncer(os.Stdout, nil)
	} else {
		logWriter = os.Stdout
	}
	toplevel.Use(skip.New(logger.New(logger.Config{
		Output: logWriter,
		Format: "${protocol} ${method} ${status} ${host} ${url} ${respHeader:Location}\n",
	}), func(c *fiber.Ctx) bool {
		return c.Hostname() == "fly-internal"
	}))
	toplevel.Use(func(c *fiber.Ctx) error {
		host := hosts[c.Hostname()]
		if host == nil {
			if runtimeConfig.RedirectOtherHostnames {
				return c.Redirect(runtimeConfig.BaseURL.JoinPath(c.OriginalURL()).String())
			} else {
				hosts[runtimeConfig.BaseURL.Host].Fiber.Handler()(c.Context())
				return nil
			}
		} else {
			host.Fiber.Handler()(c.Context())
			return nil
		}
	})

	go func() {
		err := metricServer.Listen(net.JoinHostPort(runtimeConfig.ListenAddress, "9091"))
		log.Printf("failed to start metrics server: %v", err)
	}()
	log.Fatal(toplevel.Listen(net.JoinHostPort(runtimeConfig.ListenAddress, fmt.Sprint(runtimeConfig.Port))))
}