NewServer 创建新的 API 服务器
(ctx context.Context)
| 18 | |
| 19 | // NewServer 创建新的 API 服务器 |
| 20 | func NewServer(ctx context.Context) *Server { |
| 21 | cfg := config.C().API |
| 22 | |
| 23 | factory := NewTaskFactory(ctx) |
| 24 | handlers := NewHandlers(factory) |
| 25 | |
| 26 | // 设置路由 |
| 27 | mux := http.NewServeMux() |
| 28 | |
| 29 | // 健康检查 |
| 30 | mux.HandleFunc("/health", handlers.HealthCheckHandler) |
| 31 | |
| 32 | // API v1 路由 |
| 33 | mux.HandleFunc("/api/v1/tasks", func(w http.ResponseWriter, r *http.Request) { |
| 34 | switch r.Method { |
| 35 | case http.MethodGet: |
| 36 | handlers.ListTasksHandler(w, r) |
| 37 | case http.MethodPost: |
| 38 | handlers.CreateTaskHandler(w, r) |
| 39 | default: |
| 40 | MethodNotAllowedHandler(w, r) |
| 41 | } |
| 42 | }) |
| 43 | mux.HandleFunc("/api/v1/tasks/", func(w http.ResponseWriter, r *http.Request) { |
| 44 | // 根据方法和路径分发 |
| 45 | switch r.Method { |
| 46 | case http.MethodGet: |
| 47 | handlers.GetTaskHandler(w, r) |
| 48 | case http.MethodDelete: |
| 49 | handlers.CancelTaskHandler(w, r) |
| 50 | default: |
| 51 | MethodNotAllowedHandler(w, r) |
| 52 | } |
| 53 | }) |
| 54 | mux.HandleFunc("/api/v1/storages", handlers.ListStoragesHandler) |
| 55 | mux.HandleFunc("/api/v1/task-types", handlers.GetTaskTypesHandler) |
| 56 | |
| 57 | // 404 处理 |
| 58 | mux.HandleFunc("/", NotFoundHandler) |
| 59 | |
| 60 | // Apply middleware chain. |
| 61 | var handler http.Handler = mux |
| 62 | |
| 63 | // Apply auth middleware when a token is configured. |
| 64 | token := cfg.Token |
| 65 | if token != "" { |
| 66 | handler = AuthMiddleware()(handler) |
| 67 | } |
| 68 | |
| 69 | // Add logging middleware. |
| 70 | handler = loggingMiddleware(handler) |
| 71 | |
| 72 | // Add recovery middleware. |
| 73 | handler = recoveryMiddleware(handler) |
| 74 | |
| 75 | return &Server{ |
| 76 | httpServer: &http.Server{ |
| 77 | Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), |
no test coverage detected