读取CSV文件,转换map数据。文件上传scp

This commit is contained in:
TsMask
2023-09-11 21:03:53 +08:00
parent 614e792670
commit f9596f6363
3 changed files with 97 additions and 0 deletions

View File

@@ -4,6 +4,7 @@ import (
"encoding/csv"
"os"
"path/filepath"
"strings"
"ems.agt/lib/log"
)
@@ -41,3 +42,45 @@ func WriterCSVFile(data [][]string, filePath string) error {
}
return nil
}
// 读取CSV文件转换map数据
func ReadCSVFile(filePath string) []map[string]string {
// 打开 CSV 文件
file, err := os.Open(filePath)
if err != nil {
log.Fatal("无法打开 CSV 文件:", err)
}
defer file.Close()
// 创建 CSV Reader
reader := csv.NewReader(file)
// 读取 CSV 头部行
header, err := reader.Read()
if err != nil {
log.Fatal("无法读取 CSV 头部行:", err)
}
// 创建 map 存储 CSV 数据
arr := make([]map[string]string, 0)
// 遍历 CSV 数据行
for {
// 读取一行数据
record, err := reader.Read()
if err != nil {
// 到达文件末尾或遇到错误时退出循环
break
}
// 将 CSV 数据插入到 map 中
data := make(map[string]string)
for i, value := range record {
key := strings.ToLower(header[i])
data[key] = value
}
arr = append(arr, data)
}
return arr
}

22
lib/core/file/ssh.go Normal file
View File

@@ -0,0 +1,22 @@
package file
import (
"fmt"
"os/exec"
"ems.agt/lib/core/conf"
)
// 网元NE 文件复制到远程文件夹
func FileNeSCP(neIp, filePath, dstPath string) error {
usernameNe := conf.Get("ne.user").(string)
// scp /path/to/local/file.txt user@remote-server:/path/to/remote/directory/
dstDir := fmt.Sprintf("%s@%s:%s", usernameNe, neIp, dstPath)
cmd := exec.Command("scp", "-r", filePath, dstDir)
out, err := cmd.CombinedOutput()
if err != nil {
return err
}
fmt.Println(out)
return nil
}

View File

@@ -6,6 +6,8 @@ import (
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"ems.agt/lib/core/vo"
"github.com/gorilla/mux"
@@ -67,6 +69,36 @@ func FileAttachment(w http.ResponseWriter, r *http.Request, filepath, filename s
http.ServeFile(w, r, filepath)
}
// 将文件上传保存到指定目录
// file, handler, err := r.FormFile("file")
// SaveUploadedFile uploads the form file to specific dst.
func SaveUploadedFile(r *http.Request, dst string) error {
// 解析请求中的文件
_, handler, err := r.FormFile("file")
if err != nil {
return err
}
src, err := handler.Open()
if err != nil {
return err
}
defer src.Close()
if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil {
return err
}
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, src)
return err
}
/// ==== 登录用户信息, 通过中间件后预置入
// 定义自定义类型作为键