photoprism/internal/server/server.go

79 lines
1.7 KiB
Go
Raw Normal View History

package server
import (
"context"
"fmt"
"net/http"
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)
}
}()
2021-01-10 15:28:42 +01:00
// Set http server mode.
if conf.HttpMode() != "" {
gin.SetMode(conf.HttpMode())
} else if conf.Debug() == false {
gin.SetMode(gin.ReleaseMode)
}
2021-01-10 15:28:42 +01:00
// Create router and add routing middleware.
router := gin.New()
router.Use(Logger(), Recovery())
2021-01-10 15:28:42 +01:00
// Enable http compression (if any).
switch conf.HttpCompression() {
case "gzip":
log.Infof("http: enabling gzip compression")
router.Use(gzip.Gzip(
gzip.DefaultCompression,
gzip.WithExcludedPaths([]string{
"/api/v1/t",
"/api/v1/folders/t",
"/api/v1/zip",
"/api/v1/albums",
"/api/v1/labels",
})))
2021-01-10 15:28:42 +01:00
}
// Set template directory
router.LoadHTMLGlob(conf.TemplatesPath() + "/*")
registerRoutes(router, conf)
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", conf.HttpHost(), conf.HttpPort()),
Handler: router,
}
go func() {
2021-01-10 15:28:42 +01:00
log.Infof("http: starting web server at %s", server.Addr)
if err := server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
2021-01-10 15:28:42 +01:00
log.Info("http: web server shutdown complete")
} else {
2021-01-10 15:28:42 +01:00
log.Errorf("http: web server closed unexpect: %s", err)
}
}
}()
<-ctx.Done()
2021-01-10 15:28:42 +01:00
log.Info("http: shutting down web server")
err := server.Close()
if err != nil {
2021-01-10 15:28:42 +01:00
log.Errorf("http: web server shutdown failed: %v", err)
}
}