74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
/*
|
|
Copyright CAcert Inc.
|
|
SPDX-License-Identifier: Apache-2.0
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
https://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/knadh/koanf"
|
|
)
|
|
|
|
func StartApplication(ctx context.Context, logger *slog.Logger, server *http.Server, publicURL string, config *koanf.Koanf) error {
|
|
done := make(chan bool)
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, os.Interrupt)
|
|
|
|
go func() {
|
|
<-quit
|
|
logger.Info("Server is shutting down...")
|
|
atomic.StoreInt32(&Healthy, 0)
|
|
|
|
const shutdownWaitTime = 30 * time.Second
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, shutdownWaitTime)
|
|
|
|
defer cancel()
|
|
|
|
server.SetKeepAlivesEnabled(false)
|
|
|
|
if err := server.Shutdown(ctx); err != nil {
|
|
logger.Error("Could not gracefully shutdown the server", "error", err)
|
|
}
|
|
|
|
close(done)
|
|
}()
|
|
|
|
logger.Info("Server is ready to handle requests", "public_url", publicURL)
|
|
atomic.StoreInt32(&Healthy, 1)
|
|
|
|
if err := server.ListenAndServeTLS(
|
|
config.String("server.certificate"), config.String("server.key"),
|
|
); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
logger.Error("Could not listen on requested address", "server_address", server.Addr)
|
|
|
|
return fmt.Errorf("listening failed: %w", err)
|
|
}
|
|
|
|
<-done
|
|
logger.Info("Server stopped")
|
|
|
|
return nil
|
|
}
|