package main import ( "log" "net/http" "runtime" "text/template" "time" "main/routers" "main/utils" "github.com/gorilla/mux" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) r := mux.NewRouter() // 設定中間件 r.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer utils.LogComponent(time.Now().UnixNano(), r) // 最后打印日志 w.Header().Set("Access-Control-Allow-Origin", "*") // 處理跨域請求 w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) // 處理OPTIONS請求 return } next.ServeHTTP(w, r) }) }) // 設定路由 r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("templates/index.html") t.Execute(w, nil) }) r.HandleFunc("/api/models", routers.ModelsGet).Methods("GET") r.HandleFunc("/api/models", routers.ModelsPost).Methods("POST") r.HandleFunc("/api/models/{id}", routers.ModelItemGet).Methods("GET") r.HandleFunc("/api/models/{id}", routers.ModelItemPatch).Methods("PATCH") r.HandleFunc("/api/models/{id}", routers.ModelItemDelete).Methods("DELETE") r.HandleFunc("/api/images", routers.ImagesGet).Methods("GET") r.HandleFunc("/api/images", routers.ImagesPost).Methods("POST") r.HandleFunc("/api/images/{id}", routers.ImagesItemGet).Methods("GET") r.HandleFunc("/api/images/{id}", routers.ImagesItemPatch).Methods("PATCH") r.HandleFunc("/api/images/{id}", routers.ImagesItemDelete).Methods("DELETE") r.HandleFunc("/api/tasks", routers.TasksGet).Methods("GET") r.HandleFunc("/api/tasks", routers.TasksPost).Methods("POST") r.HandleFunc("/api/tasks/{id}", routers.TasksItemGet).Methods("GET") r.HandleFunc("/api/tasks/{id}", routers.TasksItemPatch).Methods("PATCH") r.HandleFunc("/api/tasks/{id}", routers.TasksItemDelete).Methods("DELETE") r.HandleFunc("/api/params/model", routers.ParamsModelsGet).Methods("GET") log.Println("Web Server is running on http://localhost:8080") http.ListenAndServe(":8080", r) }