Redmage/server/server.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-04-07 12:11:25 +07:00
package server
import (
2024-04-07 16:06:33 +07:00
"context"
"errors"
2024-04-09 14:30:54 +07:00
"io/fs"
2024-04-29 15:18:23 +07:00
"net"
2024-04-07 12:11:25 +07:00
"net/http"
"github.com/go-chi/chi/v5"
2024-04-09 14:30:54 +07:00
"github.com/tigorlazuardi/redmage/api"
2024-04-07 12:11:25 +07:00
"github.com/tigorlazuardi/redmage/config"
2024-04-07 16:06:33 +07:00
"github.com/tigorlazuardi/redmage/pkg/caller"
"github.com/tigorlazuardi/redmage/pkg/errs"
"github.com/tigorlazuardi/redmage/pkg/log"
2024-04-09 14:30:54 +07:00
"github.com/tigorlazuardi/redmage/server/routes"
2024-04-07 12:11:25 +07:00
)
type Server struct {
2024-04-09 14:30:54 +07:00
server *http.Server
config *config.Config
PublicDir fs.FS
2024-04-07 12:11:25 +07:00
}
2024-04-07 16:06:33 +07:00
func (srv *Server) Start(exit <-chan struct{}) error {
errch := make(chan error, 1)
caller := caller.New(3)
go func() {
2024-04-29 15:18:23 +07:00
log.New(context.Background()).Caller(caller).Info(
"starting http server",
"address", "http://"+srv.server.Addr,
2024-04-29 15:18:23 +07:00
"outbound_ip", "http://"+GetOutboundIP().String()+":"+srv.config.String("http.port"),
"version", srv.config.String("runtime.version"),
2024-04-29 15:18:23 +07:00
)
2024-04-07 16:06:33 +07:00
errch <- srv.server.ListenAndServe()
}()
select {
case <-exit:
2024-04-08 15:48:45 +07:00
log.New(context.Background()).Caller(caller).Info("received exit signal. shutting down server")
2024-04-07 16:06:33 +07:00
ctx, cancel := context.WithTimeout(context.Background(), srv.config.Duration("http.shutdown_timeout"))
defer cancel()
return srv.server.Shutdown(ctx)
case err := <-errch:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return errs.Wrap(err)
}
2024-04-07 12:11:25 +07:00
}
2024-04-09 14:30:54 +07:00
func New(cfg *config.Config, api *api.API, publicDir fs.FS) *Server {
2024-04-07 12:11:25 +07:00
router := chi.NewRouter()
2024-04-09 14:30:54 +07:00
routes := routes.Routes{
API: api,
Config: cfg,
PublicDir: publicDir,
}
routes.Register(router)
2024-04-07 12:11:25 +07:00
2024-04-07 16:06:33 +07:00
server := &http.Server{
Handler: router,
Addr: cfg.String("http.host") + ":" + cfg.String("http.port"),
2024-04-07 12:11:25 +07:00
}
2024-04-07 16:06:33 +07:00
return &Server{server: server, config: cfg}
2024-04-07 12:11:25 +07:00
}
2024-04-29 15:18:23 +07:00
// Get preferred outbound ip of this machine
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
panic(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}