142 lines
3.6 KiB
Go
142 lines
3.6 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"time"
|
|
)
|
|
|
|
// Server represents an HTTP server.
|
|
type Server struct {
|
|
srv *http.Server
|
|
logger *slog.Logger
|
|
disableTls bool
|
|
tlsCertFilename string
|
|
tlsKeyFilename string
|
|
}
|
|
|
|
// New creates a new server with the given logger, address and options.
|
|
func New(logger *slog.Logger, addr string, opts ...Option) *Server {
|
|
|
|
// Set some options for TLS
|
|
tlsConfig := &tls.Config{
|
|
MinVersion: tls.VersionTLS12,
|
|
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
|
|
PreferServerCipherSuites: true,
|
|
InsecureSkipVerify: true,
|
|
CipherSuites: []uint16{
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
|
|
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
|
|
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
|
|
},
|
|
}
|
|
|
|
srv := &http.Server{
|
|
Addr: addr,
|
|
WriteTimeout: 15 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
TLSConfig: tlsConfig,
|
|
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
|
}
|
|
for _, opt := range opts {
|
|
opt(&Server{srv: srv})
|
|
}
|
|
|
|
return &Server{
|
|
srv: srv,
|
|
logger: logger,
|
|
}
|
|
}
|
|
|
|
// Option represents a server option.
|
|
type Option func(*Server)
|
|
|
|
// WithWriteTimeout sets the write timeout.
|
|
func WithWriteTimeout(timeout time.Duration) Option {
|
|
return func(s *Server) {
|
|
s.srv.WriteTimeout = timeout
|
|
}
|
|
}
|
|
|
|
// WithReadTimeout sets the read timeout.
|
|
func WithReadTimeout(timeout time.Duration) Option {
|
|
return func(s *Server) {
|
|
s.srv.ReadTimeout = timeout
|
|
}
|
|
}
|
|
|
|
// WithRouter sets the handler.
|
|
func WithRouter(handler http.Handler) Option {
|
|
return func(s *Server) {
|
|
s.srv.Handler = handler
|
|
}
|
|
}
|
|
|
|
// DisableTls sets the disable tls value
|
|
func (s *Server) DisableTls(disableTls bool) {
|
|
s.disableTls = disableTls
|
|
}
|
|
|
|
// SetCertificate sets the path to the certificate used for TLS, in PEM format
|
|
func (s *Server) SetCertificate(tlsCertFilename string) {
|
|
s.tlsCertFilename = tlsCertFilename
|
|
}
|
|
|
|
// SetPrivateKey sets the path to the private key used for TLS, in PEM format
|
|
func (s *Server) SetPrivateKey(tlsKeyFilename string) {
|
|
s.tlsKeyFilename = tlsKeyFilename
|
|
}
|
|
|
|
// StartAndWait starts the server and waits for a signal to shut down.
|
|
func (s *Server) StartAndWait() {
|
|
s.Start()
|
|
s.GracefulShutdown()
|
|
}
|
|
|
|
// Start starts the server.
|
|
func (s *Server) Start() {
|
|
|
|
go func() {
|
|
if s.disableTls {
|
|
s.logger.Info("starting server", "port", s.srv.Addr)
|
|
if err := s.srv.ListenAndServe(); err != nil {
|
|
s.logger.Warn("failed to start server", "error", err)
|
|
}
|
|
} else {
|
|
s.logger.Info("starting TLS server", "port", s.srv.Addr, "cert", s.tlsCertFilename, "key", s.tlsKeyFilename)
|
|
if err := s.srv.ListenAndServeTLS(s.tlsCertFilename, s.tlsKeyFilename); err != nil {
|
|
s.logger.Warn("failed to start server", "error", err)
|
|
}
|
|
}
|
|
|
|
}()
|
|
}
|
|
|
|
// GracefulShutdown shuts down the server gracefully.
|
|
func (s *Server) GracefulShutdown() {
|
|
c := make(chan os.Signal, 1)
|
|
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
|
|
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
|
|
signal.Notify(c, os.Interrupt)
|
|
|
|
// Block until we receive our signal.
|
|
<-c
|
|
|
|
// Create a deadline to wait for.
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
// Doesn't block if no connections, but will otherwise wait
|
|
// until the timeout deadline.
|
|
_ = s.srv.Shutdown(ctx)
|
|
// Optionally, you could run srv.Shutdown in a goroutine and block on
|
|
// <-ctx.Done() if your application should wait for other services
|
|
// to finalize based on context cancellation.
|
|
s.logger.Info("shutting down")
|
|
os.Exit(0)
|
|
}
|