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

81 lines
1.4 KiB
Go

package proxy
import (
"context"
"net/http"
"sync"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
"forge.cadoles.com/arcad/edge/pkg/proxy"
)
type ReverseProxy struct {
addr string
server *http.Server
mutex sync.RWMutex
}
func (p *ReverseProxy) Start(ctx context.Context, addr string, funcs ...proxy.OptionFunc) error {
if p.server != nil {
if err := p.Stop(); err != nil {
return errors.WithStack(err)
}
}
server := &http.Server{
Addr: addr,
}
proxy := proxy.New(funcs...)
server.Handler = proxy
p.mutex.Lock()
p.server = server
p.addr = addr
p.mutex.Unlock()
go func() {
defer func() {
if err := p.Stop(); err != nil {
logger.Error(ctx, "error while stopping gateway", logger.E(errors.WithStack(err)))
}
}()
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error(ctx, "error while listening", logger.E(errors.WithStack(err)))
}
}()
return nil
}
func (p *ReverseProxy) Running() bool {
p.mutex.RLock()
defer p.mutex.RUnlock()
return p.server != nil
}
func (p *ReverseProxy) Stop() error {
p.mutex.Lock()
defer p.mutex.Unlock()
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{}
}