github.com/anycable/anycable-go@v1.5.1/cmd/embedded-cable/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log/slog"
     7  	"net/http"
     8  	"os"
     9  	"time"
    10  
    11  	"github.com/anycable/anycable-go/cli"
    12  	_ "github.com/anycable/anycable-go/diagnostics"
    13  	"github.com/anycable/anycable-go/utils"
    14  )
    15  
    16  func main() {
    17  	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{}))
    18  
    19  	opts := []cli.Option{
    20  		cli.WithName("AnyCable"),
    21  		cli.WithDefaultRPCController(),
    22  		cli.WithDefaultBroker(),
    23  		cli.WithDefaultSubscriber(),
    24  		cli.WithTelemetry(),
    25  		cli.WithLogger(logger),
    26  	}
    27  
    28  	c := cli.NewConfig()
    29  
    30  	runner, err := cli.NewRunner(c, opts)
    31  
    32  	if err != nil {
    33  		fmt.Printf("%+v\n", err)
    34  		os.Exit(1)
    35  	}
    36  
    37  	anycable, err := runner.Embed()
    38  
    39  	if err != nil {
    40  		fmt.Printf("%+v\n", err)
    41  		os.Exit(1)
    42  	}
    43  
    44  	wsHandler, err := anycable.WebSocketHandler()
    45  
    46  	if err != nil {
    47  		fmt.Printf("%+v\n", err)
    48  		os.Exit(1)
    49  	}
    50  
    51  	seeHandler, err := anycable.SSEHandler(context.Background())
    52  
    53  	if err != nil {
    54  		fmt.Printf("%+v\n", err)
    55  		os.Exit(1)
    56  	}
    57  
    58  	broadcastHandler, err := anycable.HTTPBroadcastHandler()
    59  
    60  	if err != nil {
    61  		fmt.Printf("%+v\n", err)
    62  		os.Exit(1)
    63  	}
    64  
    65  	http.Handle("/cable", wsHandler)
    66  	http.Handle("/sse", seeHandler)
    67  	http.Handle("/broadcast", broadcastHandler)
    68  
    69  	go http.ListenAndServe(":8080", nil) // nolint:errcheck,gosec
    70  
    71  	// Graceful shutdown (to ensure AnyCable sends disconnect notices)
    72  	s := utils.NewGracefulSignals(10 * time.Second)
    73  	ch := make(chan error, 1)
    74  
    75  	s.HandleForceTerminate(func() {
    76  		logger.Warn("Immediate termination requested. Stopped")
    77  		ch <- nil
    78  	})
    79  
    80  	s.Handle(func(ctx context.Context) error {
    81  		logger.Info("Shutting down... (hit Ctrl-C to stop immediately or wait for up to 10s for graceful shutdown)")
    82  		return nil
    83  	})
    84  	s.Handle(anycable.Shutdown)
    85  	s.Handle(func(ctx context.Context) error {
    86  		ch <- nil
    87  		return nil
    88  	})
    89  
    90  	s.Listen()
    91  
    92  	<-ch
    93  }