emissary/internal/agent/controller/proxy/reverse_proxy.go

85 lines
1.5 KiB
Go
Raw Normal View History

2023-03-21 13:28:41 +01:00
package proxy
2023-02-02 10:55:24 +01:00
import (
"context"
"net/http"
2023-03-22 18:15:22 +01:00
"sync"
2023-02-02 10:55:24 +01:00
"forge.cadoles.com/Cadoles/emissary/internal/proxy"
2023-10-13 12:30:52 +02:00
"github.com/getsentry/sentry-go"
2023-02-02 10:55:24 +01:00
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
type ReverseProxy struct {
addr string
server *http.Server
2023-03-22 18:15:22 +01:00
mutex sync.RWMutex
2023-02-02 10:55:24 +01:00
}
2023-03-22 18:15:22 +01:00
func (p *ReverseProxy) Start(ctx context.Context, addr string, funcs ...proxy.OptionFunc) error {
2023-02-02 10:55:24 +01:00
if p.server != nil {
if err := p.Stop(); err != nil {
return errors.WithStack(err)
}
}
server := &http.Server{
Addr: addr,
}
2023-03-22 18:15:22 +01:00
proxy := proxy.New(funcs...)
2023-02-02 10:55:24 +01:00
server.Handler = proxy
2023-03-22 18:15:22 +01:00
p.mutex.Lock()
2023-02-02 10:55:24 +01:00
p.server = server
p.addr = addr
2023-03-22 18:15:22 +01:00
p.mutex.Unlock()
2023-02-02 10:55:24 +01:00
go func() {
2023-03-22 18:15:22 +01:00
defer func() {
if err := p.Stop(); err != nil {
2023-10-13 12:30:52 +02:00
err = errors.WithStack(err)
logger.Error(ctx, "error while stopping gateway", logger.E(err))
sentry.CaptureException(err)
2023-03-22 18:15:22 +01:00
}
}()
2023-02-02 10:55:24 +01:00
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
2023-10-13 12:30:52 +02:00
err = errors.WithStack(err)
logger.Error(ctx, "error while listening", logger.E(err))
sentry.CaptureException(err)
2023-02-02 10:55:24 +01:00
}
}()
return nil
}
2023-03-22 18:15:22 +01:00
func (p *ReverseProxy) Running() bool {
p.mutex.RLock()
defer p.mutex.RUnlock()
return p.server != nil
}
2023-02-02 10:55:24 +01:00
func (p *ReverseProxy) Stop() error {
2023-03-22 18:15:22 +01:00
p.mutex.Lock()
defer p.mutex.Unlock()
2023-02-02 10:55:24 +01:00
if p.server == nil {
return nil
}
if err := p.server.Close(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return errors.WithStack(err)
}
p.server = nil
return nil
}
func NewReverseProxy() *ReverseProxy {
return &ReverseProxy{}
}