GoDoxy/internal/server/server.go
yusing 53557e38b6 Fixed a few issues:
- Incorrect name being shown on dashboard "Proxies page"
- Apps being shown when homepage.show is false
- Load balanced routes are shown on homepage instead of the load balancer
- Route with idlewatcher will now be removed on container destroy
- Idlewatcher panic
- Performance improvement
- Idlewatcher infinitely loading
- Reload stucked / not working properly
- Streams stuck on shutdown / reload
- etc...
Added:
- support idlewatcher for loadbalanced routes
- partial implementation for stream type idlewatcher
Issues:
- graceful shutdown
2024-10-18 16:47:01 +08:00

166 lines
3.6 KiB
Go

package server
import (
"context"
"crypto/tls"
"errors"
"log"
"net/http"
"time"
"github.com/sirupsen/logrus"
"github.com/yusing/go-proxy/internal/autocert"
"github.com/yusing/go-proxy/internal/task"
)
type Server struct {
Name string
CertProvider *autocert.Provider
http *http.Server
https *http.Server
httpStarted bool
httpsStarted bool
startTime time.Time
task task.Task
}
type Options struct {
Name string
HTTPAddr string
HTTPSAddr string
CertProvider *autocert.Provider
RedirectToHTTPS bool
Handler http.Handler
}
type LogrusWrapper struct {
*logrus.Entry
}
func (l LogrusWrapper) Write(b []byte) (int, error) {
return l.Logger.WriterLevel(logrus.ErrorLevel).Write(b)
}
func NewServer(opt Options) (s *Server) {
var httpSer, httpsSer *http.Server
var httpHandler http.Handler
logger := log.Default()
logger.SetOutput(LogrusWrapper{
logrus.WithFields(logrus.Fields{"?": "server", "name": opt.Name}),
})
certAvailable := false
if opt.CertProvider != nil {
_, err := opt.CertProvider.GetCert(nil)
certAvailable = err == nil
}
if certAvailable && opt.RedirectToHTTPS && opt.HTTPSAddr != "" {
httpHandler = redirectToTLSHandler(opt.HTTPSAddr)
} else {
httpHandler = opt.Handler
}
if opt.HTTPAddr != "" {
httpSer = &http.Server{
Addr: opt.HTTPAddr,
Handler: httpHandler,
ErrorLog: logger,
}
}
if certAvailable && opt.HTTPSAddr != "" {
httpsSer = &http.Server{
Addr: opt.HTTPSAddr,
Handler: opt.Handler,
ErrorLog: logger,
TLSConfig: &tls.Config{
GetCertificate: opt.CertProvider.GetCert,
},
}
}
return &Server{
Name: opt.Name,
CertProvider: opt.CertProvider,
http: httpSer,
https: httpsSer,
task: task.GlobalTask(opt.Name + " server"),
}
}
// Start will start the http and https servers.
//
// If both are not set, this does nothing.
//
// Start() is non-blocking.
func (s *Server) Start() {
if s.http == nil && s.https == nil {
return
}
s.startTime = time.Now()
if s.http != nil {
s.httpStarted = true
logrus.Printf("starting http %s server on %s", s.Name, s.http.Addr)
go func() {
s.handleErr("http", s.http.ListenAndServe())
}()
}
if s.https != nil {
s.httpsStarted = true
logrus.Printf("starting https %s server on %s", s.Name, s.https.Addr)
go func() {
s.handleErr("https", s.https.ListenAndServeTLS(s.CertProvider.GetCertPath(), s.CertProvider.GetKeyPath()))
}()
}
s.task.OnComplete("stop server", s.stop)
}
func (s *Server) stop() {
if s.http == nil && s.https == nil {
return
}
if s.http != nil && s.httpStarted {
s.handleErr("http", s.http.Shutdown(s.task.Context()))
s.httpStarted = false
}
if s.https != nil && s.httpsStarted {
s.handleErr("https", s.https.Shutdown(s.task.Context()))
s.httpsStarted = false
}
}
func (s *Server) Uptime() time.Duration {
return time.Since(s.startTime)
}
func (s *Server) handleErr(scheme string, err error) {
switch {
case err == nil, errors.Is(err, http.ErrServerClosed), errors.Is(err, context.Canceled):
return
default:
logrus.Fatalf("%s server %s error: %s", scheme, s.Name, err)
}
}
func redirectToTLSHandler(port string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.URL.Scheme = "https"
r.URL.Host = r.URL.Hostname() + port
var redirectCode int
if r.Method == http.MethodGet {
redirectCode = http.StatusMovedPermanently
} else {
redirectCode = http.StatusPermanentRedirect
}
http.Redirect(w, r, r.URL.String(), redirectCode)
}
}
var logger = logrus.WithField("module", "server")