package main import ( "context" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" "cdr.dev/slog" "forge.cadoles.com/wpetit/go-tunnel" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/logger" ) const sharedKey = "go-tunnel" const salt = "go-tunnel" var registry = NewRegistry() func main() { ctx := context.Background() logger.SetLevel(slog.LevelDebug) server := tunnel.NewServer( tunnel.WithServerAESBlockCrypt(sharedKey, salt), tunnel.WithServerOnClientAuth(registry.OnClientAuth), tunnel.WithServerOnClientDisconnect(registry.OnClientDisconnect), ) go func() { if err := server.Listen(ctx); err != nil { logger.Fatal(ctx, "error while listening", logger.E(err)) } }() if err := http.ListenAndServe(":3003", http.HandlerFunc(handleRequest)); err != nil { logger.Fatal(ctx, "error while listening", logger.E(err)) } } func handleRequest(w http.ResponseWriter, r *http.Request) { subdomains := strings.SplitN(r.Host, ".", 2) if len(subdomains) < 2 { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } clientID := subdomains[0] remoteClient := registry.Get(clientID) if remoteClient == nil { http.Error(w, http.StatusText(http.StatusBadGateway), http.StatusBadGateway) return } target, err := url.Parse("http://localhost:3000") if err != nil { logger.Fatal(r.Context(), "could not parse url", logger.E(err)) } reverse := httputil.NewSingleHostReverseProxy(target) reverse.Transport = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) { conn, err := remoteClient.Proxy(ctx, network, addr) if err != nil { return nil, errors.WithStack(err) } return conn, nil }, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } reverse.ServeHTTP(w, r) }