package handler import ( "encoding/json" "net/http" "os" "path/filepath" "strings" "xtcfs/config" "xtcfs/util" ) // json 结构体 type Response struct { Status string `json:"status"` //状态 Data FilesListJson `json:"data"` //目录下的文件 Curdir string `json:"curdir"` // 扫描的目录 WorksDir string `json:"workdir"` //监听目录 } // 文件输出的结构 type FileJson struct { Fname string `json:"fname"` Dirflag bool `json:"dirflag"` } type FilesListJson struct { Flist []FileJson `json:"list"` } // 遍历监视目录,发送到json中 func SerInfo(w http.ResponseWriter, r *http.Request) { // 监听的目录通过?p=的方式传入 urlpath := r.URL.Query().Get("p") // 防止逃逸,造成漏洞 if strings.Contains(urlpath, "../") { urlpath = "." } // 监听的根目录 realFilePath := filepath.Join(config.G.FilePath, urlpath) // 时间目录的情况 fileInfo, err := os.Stat(realFilePath) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // list json var flist FilesListJson //针对目录的情况才输出 // todo 如果是文件的话 暂时不处理 if fileInfo.IsDir() { // 遍历目录 files, err := os.ReadDir(realFilePath) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 遍历 for _, v := range files { flist.Flist = append(flist.Flist, FileJson{Fname: v.Name(), Dirflag: v.IsDir()}) } } // respone file list response := Response{ Status: "success", Curdir: urlpath, WorksDir: config.G.FilePath, Data: flist, } // 开启跨域 util.CorsHadler(w, r) json.NewEncoder(w).Encode(response) }