photoprism/internal/server/server.go

107 lines
2.6 KiB
Go
Raw Normal View History

package server
import (
"context"
"fmt"
"net/http"
"time"
2021-01-10 15:28:42 +01:00
"github.com/gin-contrib/gzip"
2018-09-06 14:47:32 +02:00
"github.com/gin-gonic/gin"
"github.com/photoprism/photoprism/internal/config"
"github.com/photoprism/photoprism/internal/event"
)
var log = event.Log
2018-11-06 19:02:03 +01:00
// Start the REST API server using the configuration provided
func Start(ctx context.Context, conf *config.Config) {
defer func() {
if err := recover(); err != nil {
log.Error(err)
}
}()
start := time.Now()
2021-10-17 16:48:53 +02:00
// Set HTTP server mode.
if conf.HttpMode() != "" {
gin.SetMode(conf.HttpMode())
} else if conf.Debug() == false {
gin.SetMode(gin.ReleaseMode)
}
2021-10-17 16:48:53 +02:00
// Create new HTTP router engine without standard middleware.
router := gin.New()
2021-10-17 16:48:53 +02:00
// Register logger middleware.
router.Use(Logger(), Recovery())
2021-10-17 16:48:53 +02:00
// Register security middleware.
router.Use(Security(SecurityOptions{
IsDevelopment: gin.Mode() != gin.ReleaseMode || conf.Test(),
AllowedHosts: []string{},
SSLRedirect: false,
SSLHost: "",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
STSSeconds: 0,
STSIncludeSubdomains: false,
FrameDeny: true,
ContentTypeNosniff: false,
BrowserXssFilter: false,
ContentSecurityPolicy: "frame-ancestors 'none';",
}))
// Enable HTTP compression?
2021-01-10 15:28:42 +01:00
switch conf.HttpCompression() {
case "gzip":
log.Infof("server: enabling gzip compression")
2021-01-10 15:28:42 +01:00
router.Use(gzip.Gzip(
gzip.DefaultCompression,
gzip.WithExcludedPaths([]string{
2021-07-05 16:41:43 +02:00
conf.BaseUri(config.ApiUri + "/t"),
conf.BaseUri(config.ApiUri + "/folders/t"),
conf.BaseUri(config.ApiUri + "/zip"),
conf.BaseUri(config.ApiUri + "/albums"),
conf.BaseUri(config.ApiUri + "/labels"),
conf.BaseUri(config.ApiUri + "/videos"),
})))
2021-01-10 15:28:42 +01:00
}
// Find and load templates.
router.LoadHTMLFiles(conf.TemplateFiles()...)
2021-10-17 16:48:53 +02:00
// Register HTTP route handlers.
registerRoutes(router, conf)
2021-10-17 16:48:53 +02:00
// Create new HTTP server instance.
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", conf.HttpHost(), conf.HttpPort()),
Handler: router,
}
log.Debugf("server: successfully initialized [%s]", time.Since(start))
2021-10-17 16:48:53 +02:00
// Start HTTP server.
go func() {
log.Infof("server: listening at %s", server.Addr)
if err := server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
log.Info("server: shutdown complete")
} else {
log.Errorf("server: %s", err)
}
}
}()
2021-10-17 16:48:53 +02:00
// Graceful HTTP server shutdown.
<-ctx.Done()
log.Info("server: shutting down")
err := server.Close()
if err != nil {
log.Errorf("server: shutdown failed (%s)", err)
}
}