2018-07-20 14:13:52 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2019-06-03 22:58:15 +02:00
|
|
|
"context"
|
2018-07-20 14:13:52 +02:00
|
|
|
"fmt"
|
2019-05-04 13:29:32 +02:00
|
|
|
"net/http"
|
2018-10-31 07:14:33 +01:00
|
|
|
|
2018-09-06 14:47:32 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
2019-05-06 23:18:10 +02:00
|
|
|
"github.com/photoprism/photoprism/internal/config"
|
2019-12-02 00:30:58 +01:00
|
|
|
"github.com/photoprism/photoprism/internal/event"
|
2018-07-20 14:13:52 +02:00
|
|
|
)
|
|
|
|
|
2019-12-02 00:30:58 +01:00
|
|
|
var log = event.Log
|
|
|
|
|
2018-11-06 19:02:03 +01:00
|
|
|
// Start the REST API server using the configuration provided
|
2019-06-03 22:58:15 +02:00
|
|
|
func Start(ctx context.Context, conf *config.Config) {
|
2020-01-21 15:12:26 +01:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2019-05-06 23:18:10 +02:00
|
|
|
if conf.HttpServerMode() != "" {
|
|
|
|
gin.SetMode(conf.HttpServerMode())
|
|
|
|
} else if conf.Debug() == false {
|
2018-09-13 11:34:56 +02:00
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
}
|
|
|
|
|
2019-05-04 13:29:32 +02:00
|
|
|
router := gin.New()
|
2020-01-21 15:12:26 +01:00
|
|
|
router.Use(Logger(), Recovery())
|
2018-07-20 14:13:52 +02:00
|
|
|
|
2018-09-24 11:27:46 +02:00
|
|
|
// Set template directory
|
2019-05-06 23:18:10 +02:00
|
|
|
router.LoadHTMLGlob(conf.HttpTemplatesPath() + "/*")
|
2018-09-24 11:27:46 +02:00
|
|
|
|
2019-05-06 23:18:10 +02:00
|
|
|
registerRoutes(router, conf)
|
2018-07-20 14:13:52 +02:00
|
|
|
|
2019-05-04 13:29:32 +02:00
|
|
|
server := &http.Server{
|
2019-05-06 23:18:10 +02:00
|
|
|
Addr: fmt.Sprintf("%s:%d", conf.HttpServerHost(), conf.HttpServerPort()),
|
2019-05-04 13:29:32 +02:00
|
|
|
Handler: router,
|
2019-05-01 14:54:11 +02:00
|
|
|
}
|
2019-05-04 13:29:32 +02:00
|
|
|
|
|
|
|
go func() {
|
2020-02-05 23:05:37 +01:00
|
|
|
log.Infof("starting web server at %s", server.Addr)
|
|
|
|
|
2019-06-03 22:58:15 +02:00
|
|
|
if err := server.ListenAndServe(); err != nil {
|
|
|
|
if err == http.ErrServerClosed {
|
2019-06-04 00:22:25 +02:00
|
|
|
log.Info("web server shutdown complete")
|
2019-06-03 22:58:15 +02:00
|
|
|
} else {
|
|
|
|
log.Errorf("web server closed unexpect: %s", err)
|
|
|
|
}
|
2019-05-04 13:29:32 +02:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2019-06-03 22:58:15 +02:00
|
|
|
<-ctx.Done()
|
2019-06-04 00:22:25 +02:00
|
|
|
log.Info("shutting down web server")
|
2019-06-03 22:58:15 +02:00
|
|
|
err := server.Close()
|
|
|
|
if err != nil {
|
2019-06-04 00:22:25 +02:00
|
|
|
log.Errorf("web server shutdown failed: %v", err)
|
2019-05-04 13:29:32 +02:00
|
|
|
}
|
2018-09-27 08:59:53 +02:00
|
|
|
}
|