2018-07-20 14:13:52 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2019-05-04 13:29:32 +02:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
2018-10-31 07:14:33 +01:00
|
|
|
|
2018-09-06 14:47:32 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
2019-05-03 18:57:28 +02:00
|
|
|
"github.com/photoprism/photoprism/internal/context"
|
2019-05-01 14:54:11 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
2018-07-20 14:13:52 +02:00
|
|
|
)
|
|
|
|
|
2018-11-06 19:02:03 +01:00
|
|
|
// Start the REST API server using the configuration provided
|
2019-05-03 18:57:28 +02:00
|
|
|
func Start(ctx *context.Context) {
|
|
|
|
if ctx.HttpServerMode() != "" {
|
|
|
|
gin.SetMode(ctx.HttpServerMode())
|
|
|
|
} else if ctx.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()
|
|
|
|
router.Use(gin.Logger(), gin.Recovery())
|
2018-07-20 14:13:52 +02:00
|
|
|
|
2018-09-24 11:27:46 +02:00
|
|
|
// Set template directory
|
2019-05-04 13:29:32 +02:00
|
|
|
router.LoadHTMLGlob(ctx.HttpTemplatesPath() + "/*")
|
2018-09-24 11:27:46 +02:00
|
|
|
|
2019-05-04 13:29:32 +02:00
|
|
|
registerRoutes(router, ctx)
|
2018-07-20 14:13:52 +02:00
|
|
|
|
2019-05-04 13:29:32 +02:00
|
|
|
server := &http.Server{
|
|
|
|
Addr: fmt.Sprintf("%s:%d", ctx.HttpServerHost(), ctx.HttpServerPort()),
|
|
|
|
Handler: router,
|
2019-05-01 14:54:11 +02:00
|
|
|
}
|
2019-05-04 13:29:32 +02:00
|
|
|
|
|
|
|
quit := make(chan os.Signal)
|
|
|
|
|
|
|
|
/*
|
|
|
|
TODO: Use context for graceful shutdown of all services and add HTTP / TiDB server tests
|
|
|
|
|
|
|
|
See
|
|
|
|
- https://github.com/gin-gonic/gin/blob/dfe37ea6f1b9127be4cff4822a1308b4349444e0/examples/graceful-shutdown/graceful-shutdown/server.go
|
|
|
|
- https://stackoverflow.com/questions/45500836/close-multiple-goroutine-if-an-error-occurs-in-one-in-go
|
|
|
|
*/
|
|
|
|
|
|
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-quit
|
|
|
|
log.Info("received interrupt signal - shutting down")
|
|
|
|
|
2019-05-04 17:34:51 +02:00
|
|
|
ctx.Shutdown()
|
2019-05-04 13:29:32 +02:00
|
|
|
|
|
|
|
if err := server.Close(); err != nil {
|
|
|
|
log.Errorf("server close: %s", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if err := server.ListenAndServe(); err != nil {
|
|
|
|
if err == http.ErrServerClosed {
|
|
|
|
log.Info("web server closed")
|
|
|
|
} else {
|
|
|
|
log.Errorf("web server closed unexpect: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Info("please come back another time")
|
|
|
|
|
2019-05-04 17:34:51 +02:00
|
|
|
time.Sleep(2 * time.Second)
|
2018-09-27 08:59:53 +02:00
|
|
|
}
|