|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + "syscall" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/ag-ui-protocol/ag-ui/sdks/community/go/example/server/internal/config" |
| 13 | + "github.com/ag-ui-protocol/ag-ui/sdks/community/go/example/server/internal/mcp" |
| 14 | + "github.com/ag-ui-protocol/ag-ui/sdks/community/go/example/server/internal/routes" |
| 15 | + "github.com/gofiber/fiber/v3" |
| 16 | + "github.com/gofiber/fiber/v3/middleware/cors" |
| 17 | + "github.com/gofiber/fiber/v3/middleware/requestid" |
| 18 | + "github.com/sirupsen/logrus" |
| 19 | +) |
| 20 | + |
| 21 | +func newErrorHandler() fiber.ErrorHandler { |
| 22 | + return func(c fiber.Ctx, err error) error { |
| 23 | + code := fiber.StatusInternalServerError |
| 24 | + var ferr *fiber.Error |
| 25 | + if errors.As(err, &ferr) { |
| 26 | + code = ferr.Code |
| 27 | + } |
| 28 | + |
| 29 | + entry := logrus.NewEntry(logrus.StandardLogger()) |
| 30 | + entry.WithFields(logrus.Fields{ |
| 31 | + "error": err.Error(), |
| 32 | + "status": code, |
| 33 | + }).Error("Request error") |
| 34 | + |
| 35 | + return c.Status(code).JSON(fiber.Map{ |
| 36 | + "error": true, |
| 37 | + "message": err.Error(), |
| 38 | + }) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func registerRoutes(app *fiber.App, cfg *config.Config) { |
| 43 | + |
| 44 | + // Basic info route |
| 45 | + app.Get("/", func(c fiber.Ctx) error { |
| 46 | + return c.JSON(fiber.Map{ |
| 47 | + "message": "AG-UI Go Example Server is running!", |
| 48 | + "path": c.Path(), |
| 49 | + "method": c.Method(), |
| 50 | + "headers": c.GetReqHeaders(), |
| 51 | + }) |
| 52 | + }) |
| 53 | + |
| 54 | + if !cfg.EnableSSE { |
| 55 | + return |
| 56 | + } |
| 57 | + |
| 58 | + // Feature routes |
| 59 | + app.Post("/agentic", routes.AgenticHandler(cfg)) |
| 60 | +} |
| 61 | + |
| 62 | +func logConfig(logger *logrus.Logger, cfg *config.Config) { |
| 63 | + logger.WithFields(logrus.Fields{ |
| 64 | + "host": cfg.Host, |
| 65 | + "port": cfg.Port, |
| 66 | + "log_level": cfg.LogLevel, |
| 67 | + "enable_sse": cfg.EnableSSE, |
| 68 | + "read_timeout": cfg.ReadTimeout, |
| 69 | + "write_timeout": cfg.WriteTimeout, |
| 70 | + "sse_keepalive": cfg.SSEKeepAlive, |
| 71 | + "cors_enabled": cfg.CORSEnabled, |
| 72 | + "streaming_chunk_delay": cfg.StreamingChunkDelay, |
| 73 | + }).Info("Server configuration loaded") |
| 74 | +} |
| 75 | + |
| 76 | +func createApp(cfg *config.Config, logger *logrus.Logger) *fiber.App { |
| 77 | + app := fiber.New(fiber.Config{ |
| 78 | + AppName: "AG-UI Example Server", |
| 79 | + ReadTimeout: cfg.ReadTimeout, |
| 80 | + WriteTimeout: cfg.WriteTimeout, |
| 81 | + ErrorHandler: newErrorHandler(), |
| 82 | + }) |
| 83 | + |
| 84 | + // Middleware |
| 85 | + app.Use(requestid.New()) |
| 86 | + |
| 87 | + // CORS |
| 88 | + if cfg.CORSEnabled { |
| 89 | + app.Use(cors.New(cors.Config{ |
| 90 | + AllowOrigins: cfg.CORSAllowedOrigins, |
| 91 | + AllowMethods: []string{"GET", "POST", "HEAD", "PUT", "DELETE", "PATCH", "OPTIONS"}, |
| 92 | + AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Request-ID"}, |
| 93 | + AllowCredentials: false, |
| 94 | + })) |
| 95 | + } |
| 96 | + |
| 97 | + // Content negotiation |
| 98 | + //app.Use(encoding.ContentNegotiationMiddleware(encoding.ContentNegotiationConfig{ |
| 99 | + // DefaultContentType: "application/json", |
| 100 | + // SupportedTypes: []string{"application/json", "application/vnd.ag-ui+json"}, |
| 101 | + // EnableLogging: cfg.LogLevel == "debug", |
| 102 | + //})) |
| 103 | + |
| 104 | + // Routes |
| 105 | + registerRoutes(app, cfg) |
| 106 | + |
| 107 | + return app |
| 108 | +} |
| 109 | + |
| 110 | +func main() { |
| 111 | + // Load configuration with proper precedence: flags > env > defaults |
| 112 | + cfg, err := config.LoadConfig() |
| 113 | + if err != nil { |
| 114 | + fmt.Fprintf(os.Stderr, "Failed to load configuration: %v\n", err) |
| 115 | + os.Exit(1) |
| 116 | + } |
| 117 | + |
| 118 | + // Set up structured logging with logrus |
| 119 | + logger := logrus.New() |
| 120 | + |
| 121 | + // Log the effective configuration |
| 122 | + logConfig(logger, cfg) |
| 123 | + |
| 124 | + app := createApp(cfg, logger) |
| 125 | + |
| 126 | + // Start server in a goroutine |
| 127 | + serverAddr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port) |
| 128 | + |
| 129 | + go func() { |
| 130 | + logger.WithField("address", serverAddr).Info("Starting server") |
| 131 | + if err := app.Listen(serverAddr); err != nil { |
| 132 | + logger.WithError(err).Error("Server failed to start") |
| 133 | + os.Exit(1) |
| 134 | + } |
| 135 | + }() |
| 136 | + |
| 137 | + logger.WithField("address", serverAddr).Info("Server started successfully") |
| 138 | + |
| 139 | + // Start mcp in a goroutine |
| 140 | + mcpServer, err := mcp.NewServer(mcp.DefaultPort) |
| 141 | + if err != nil { |
| 142 | + logger.WithError(err).Error("Failed to create MCP server") |
| 143 | + os.Exit(1) |
| 144 | + } |
| 145 | + go func() { |
| 146 | + err := mcpServer.Start() |
| 147 | + if err != nil { |
| 148 | + logger.WithError(err).Error("MCP server failed to start") |
| 149 | + os.Exit(1) |
| 150 | + } |
| 151 | + }() |
| 152 | + |
| 153 | + // Wait for interrupt signal to gracefully shutdown the server |
| 154 | + quit := make(chan os.Signal, 1) |
| 155 | + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) |
| 156 | + <-quit |
| 157 | + |
| 158 | + logger.Info("Shutting down server...") |
| 159 | + |
| 160 | + // Graceful shutdown with timeout |
| 161 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 162 | + defer cancel() |
| 163 | + |
| 164 | + err = mcpServer.Shutdown(ctx) |
| 165 | + if err != nil { |
| 166 | + logger.WithError(err).Error("MCP server shutdown error") |
| 167 | + } |
| 168 | + |
| 169 | + if err = app.ShutdownWithContext(ctx); err != nil { |
| 170 | + logger.WithError(err).Error("Server shutdown error") |
| 171 | + os.Exit(1) |
| 172 | + } |
| 173 | + |
| 174 | + logger.Info("Server shutdown complete") |
| 175 | +} |
0 commit comments