package main import ( "encoding/json" "fmt" "log" "net/http" "strings" "imuslab.com/bokofs/bokofsd/mod/diskinfo" ) /* API Router This module handle routing of the API calls */ // Primary handler for the API router func HandlerAPIcalls() http.Handler { return http.StripPrefix("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get the disk ID from the URL path pathParts := strings.Split(r.URL.Path, "/") if len(pathParts) < 2 { http.Error(w, "Bad Request", http.StatusBadRequest) return } diskID := pathParts[1] if diskID == "" { http.Error(w, "Bad Request", http.StatusBadRequest) return } if diskID == "system" { HandleSystemAPIcalls().ServeHTTP(w, r) return } fmt.Fprintf(w, "API call for disk ID: %s\n", diskID) })) } // Handler for system API calls func HandleSystemAPIcalls() http.Handler { return http.StripPrefix("/system/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //Check the next part of the URL pathParts := strings.Split(r.URL.Path, "/") subPath := pathParts[0] switch subPath { case "diskinfo": if len(pathParts) < 2 { http.Error(w, "Bad Request - Invalid disk name", http.StatusBadRequest) return } diskID := pathParts[1] if diskID == "" { http.Error(w, "Bad Request - Invalid disk name", http.StatusBadRequest) return } if !diskinfo.DevicePathIsValidDisk(diskID) { log.Println("Invalid disk ID:", diskID) http.Error(w, "Bad Request", http.StatusBadRequest) return } // Handle diskinfo API calls targetDiskInfo, err := diskinfo.GetDiskInfo(diskID) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } // Convert the disk info to JSON and write it to the response js, _ := json.Marshal(targetDiskInfo) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(js) return case "partinfo": if len(pathParts) < 2 { http.Error(w, "Bad Request - Missing parition name", http.StatusBadRequest) return } partID := pathParts[1] if partID == "" { http.Error(w, "Bad Request - Missing parition name", http.StatusBadRequest) return } if !diskinfo.DevicePathIsValidPartition(partID) { log.Println("Invalid partition name:", partID) http.Error(w, "Bad Request - Invalid parition name", http.StatusBadRequest) return } // Handle partinfo API calls targetPartInfo, err := diskinfo.GetPartitionInfo(partID) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } // Convert the partition info to JSON and write it to the response js, _ := json.Marshal(targetPartInfo) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(js) return case "partlist": // Handle partlist API calls return case "diskusage": // Handle diskusage API calls fmt.Fprintln(w, "Disk usage API call") default: fmt.Println("Unknown API call:", subPath) http.Error(w, "Not Found", http.StatusNotFound) } })) }