rebound/server.go

91 lines
1.6 KiB
Go
Raw Normal View History

2023-09-09 04:00:00 +02:00
package rebound
import (
"net"
"forge.cadoles.com/wpetit/rebound/http"
"forge.cadoles.com/wpetit/rebound/ssh"
2023-09-09 04:00:00 +02:00
"github.com/pkg/errors"
)
type Server struct {
listener net.Listener
opts *Options
2023-09-09 04:00:00 +02:00
}
func (s *Server) Start() error {
s.log("[INFO] listening on %s", s.opts.Address)
2023-09-09 04:00:00 +02:00
listener, err := net.Listen("tcp", s.opts.Address)
if err != nil {
2023-09-09 04:00:00 +02:00
return errors.WithStack(err)
}
s.listener = listener
2023-09-09 04:00:00 +02:00
sshListener, httpListener := s.muxListener(listener)
2023-09-09 04:00:00 +02:00
go func() {
defer listener.Close()
2023-09-09 04:00:00 +02:00
server := ssh.NewServer(
ssh.WithHostKey(s.opts.SSH.HostKey),
ssh.WithPublicHost(s.opts.SSH.PublicHost),
ssh.WithPublicPort(s.opts.SSH.PublicPort),
ssh.WithSockDir(s.opts.SSH.SockDir),
ssh.WithLogger(s.opts.SSH.Logger),
)
2023-09-09 04:00:00 +02:00
if err := server.Serve(sshListener); err != nil {
s.log("[ERROR] %+v", errors.WithStack(err))
listener.Close()
}
}()
2023-09-09 04:00:00 +02:00
go func() {
defer listener.Close()
2023-09-09 04:00:00 +02:00
server := http.NewServer(
http.WithCustomDir(s.opts.HTTP.CustomDir),
http.WithTemplateData(s.opts.HTTP.TemplateData),
http.WithLogger(s.opts.HTTP.Logger),
)
2023-09-09 04:00:00 +02:00
if err := server.Serve(httpListener); err != nil {
s.log("[ERROR] %+v", errors.WithStack(err))
}
}()
2023-09-09 04:00:00 +02:00
return nil
}
func (s *Server) Stop() error {
if s.listener == nil {
return nil
2023-09-09 04:00:00 +02:00
}
if err := s.listener.Close(); err != nil {
return errors.WithStack(err)
2023-09-09 04:00:00 +02:00
}
s.listener = nil
return nil
2023-09-09 04:00:00 +02:00
}
func (s *Server) log(message string, args ...any) {
s.opts.Logger(message, args...)
}
func NewServer(funcs ...OptionFunc) *Server {
opts := DefaultOptions()
for _, fn := range funcs {
fn(opts)
}
return &Server{
opts: opts,
2023-09-09 04:00:00 +02:00
}
}