2026-06-15 17:50:39 +08:00

91 lines
2.6 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"droboticflow/internal/ai"
"droboticflow/internal/api"
"droboticflow/internal/config"
"droboticflow/internal/retry"
"droboticflow/internal/store"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func connectMongo(ctx context.Context, mongoURI string, attempts int, delay time.Duration) (*mongo.Client, error) {
return retry.Do(ctx, attempts, delay, "mongodb connection", func(ctx context.Context, _ int) (*mongo.Client, error) {
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
if err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
_ = client.Disconnect(ctx)
return nil, err
}
return client, nil
})
}
func spaHandler(apiHandler http.Handler, distDir string) http.Handler {
fileServer := http.FileServer(http.Dir(distDir))
indexPath := filepath.Join(distDir, "index.html")
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if strings.HasPrefix(request.URL.Path, "/api/") || strings.HasPrefix(request.URL.Path, "/worker-api/") {
apiHandler.ServeHTTP(writer, request)
return
}
if request.URL.Path == "/" {
fileServer.ServeHTTP(writer, request)
return
}
targetPath := filepath.Join(distDir, filepath.Clean(request.URL.Path))
if _, err := os.Stat(targetPath); err == nil {
fileServer.ServeHTTP(writer, request)
return
}
http.ServeFile(writer, request, indexPath)
})
}
func main() {
ctx := context.Background()
cfg := config.Load()
client, err := connectMongo(ctx, cfg.MongoURI, cfg.MongoConnectRetries, time.Duration(cfg.MongoConnectRetryDelayMS)*time.Millisecond)
if err != nil {
fmt.Printf("[api] failed to connect mongo: %v\n", err)
os.Exit(1)
}
defer func() {
_ = client.Disconnect(context.Background())
}()
dataStore := store.NewMongoStore(client.Database(cfg.MongoDB))
if err := dataStore.EnsureIndexes(ctx); err != nil {
fmt.Printf("[api] failed to ensure mongo indexes: %v\n", err)
os.Exit(1)
}
aiService := ai.NewService(cfg.AIAPIBaseURL, cfg.AIAPIKey, cfg.AIModel)
handler := spaHandler(api.NewHandler(dataStore, aiService), cfg.DistDir)
server := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%d", cfg.Port),
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
}
fmt.Printf("[api] listening on http://0.0.0.0:%d\n", cfg.Port)
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
fmt.Printf("[api] failed to start: %v\n", err)
os.Exit(1)
}
}