file.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. package file
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "io/ioutil"
  10. "log"
  11. "mime/multipart"
  12. "os"
  13. "path"
  14. path2 "path"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "github.com/mholt/archiver/v3"
  19. )
  20. // GetSize get the file size
  21. func GetSize(f multipart.File) (int, error) {
  22. content, err := ioutil.ReadAll(f)
  23. return len(content), err
  24. }
  25. // GetExt get the file ext
  26. func GetExt(fileName string) string {
  27. return path.Ext(fileName)
  28. }
  29. // CheckNotExist check if the file exists
  30. func CheckNotExist(src string) bool {
  31. _, err := os.Stat(src)
  32. return os.IsNotExist(err)
  33. }
  34. // CheckPermission check if the file has permission
  35. func CheckPermission(src string) bool {
  36. _, err := os.Stat(src)
  37. return os.IsPermission(err)
  38. }
  39. // IsNotExistMkDir create a directory if it does not exist
  40. func IsNotExistMkDir(src string) error {
  41. if notExist := CheckNotExist(src); notExist {
  42. if err := MkDir(src); err != nil {
  43. return err
  44. }
  45. }
  46. return nil
  47. }
  48. // MkDir create a directory
  49. func MkDir(src string) error {
  50. err := os.MkdirAll(src, os.ModePerm)
  51. if err != nil {
  52. return err
  53. }
  54. os.Chmod(src, 0o777)
  55. return nil
  56. }
  57. // RMDir remove a directory
  58. func RMDir(src string) error {
  59. err := os.RemoveAll(src)
  60. if err != nil {
  61. return err
  62. }
  63. os.Remove(src)
  64. return nil
  65. }
  66. // Open a file according to a specific mode
  67. func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
  68. f, err := os.OpenFile(name, flag, perm)
  69. if err != nil {
  70. return nil, err
  71. }
  72. return f, nil
  73. }
  74. // MustOpen maximize trying to open the file
  75. func MustOpen(fileName, filePath string) (*os.File, error) {
  76. //dir, err := os.Getwd()
  77. //if err != nil {
  78. // return nil, fmt.Errorf("os.Getwd err: %v", err)
  79. //}
  80. src := filePath
  81. perm := CheckPermission(src)
  82. if perm == true {
  83. return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
  84. }
  85. err := IsNotExistMkDir(src)
  86. if err != nil {
  87. return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
  88. }
  89. f, err := Open(src+fileName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0o644)
  90. if err != nil {
  91. return nil, fmt.Errorf("Fail to OpenFile :%v", err)
  92. }
  93. return f, nil
  94. }
  95. // 判断所给路径文件/文件夹是否存在
  96. func Exists(path string) bool {
  97. _, err := os.Stat(path) // os.Stat获取文件信息
  98. if err != nil {
  99. if os.IsExist(err) {
  100. return true
  101. }
  102. return false
  103. }
  104. return true
  105. }
  106. // 判断所给路径是否为文件夹
  107. func IsDir(path string) bool {
  108. s, err := os.Stat(path)
  109. if err != nil {
  110. return false
  111. }
  112. return s.IsDir()
  113. }
  114. // 判断所给路径是否为文件
  115. func IsFile(path string) bool {
  116. return !IsDir(path)
  117. }
  118. func CreateFile(path string) error {
  119. file, err := os.Create(path)
  120. if err != nil {
  121. return err
  122. }
  123. defer file.Close()
  124. return nil
  125. }
  126. func CreateFileAndWriteContent(path string, content string) error {
  127. file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o666)
  128. if err != nil {
  129. return err
  130. }
  131. defer file.Close()
  132. write := bufio.NewWriter(file)
  133. write.WriteString(content)
  134. write.Flush()
  135. return nil
  136. }
  137. // IsNotExistMkDir create a directory if it does not exist
  138. func IsNotExistCreateFile(src string) error {
  139. if notExist := CheckNotExist(src); notExist {
  140. if err := CreateFile(src); err != nil {
  141. return err
  142. }
  143. }
  144. return nil
  145. }
  146. func ReadFullFile(path string) []byte {
  147. file, err := os.Open(path)
  148. if err != nil {
  149. return []byte("")
  150. }
  151. defer file.Close()
  152. content, err := ioutil.ReadAll(file)
  153. if err != nil {
  154. return []byte("")
  155. }
  156. return content
  157. }
  158. // File copies a single file from src to dst
  159. func CopyFile(src, dst, style string) error {
  160. var err error
  161. var srcfd *os.File
  162. var dstfd *os.File
  163. var srcinfo os.FileInfo
  164. lastPath := src[strings.LastIndex(src, "/")+1:]
  165. if !strings.HasSuffix(dst, "/") {
  166. dst += "/"
  167. }
  168. dst += lastPath
  169. if Exists(dst) {
  170. if style == "skip" {
  171. return nil
  172. } else {
  173. os.Remove(dst)
  174. }
  175. }
  176. if srcfd, err = os.Open(src); err != nil {
  177. return err
  178. }
  179. defer srcfd.Close()
  180. if dstfd, err = os.Create(dst); err != nil {
  181. return err
  182. }
  183. defer dstfd.Close()
  184. if _, err = io.Copy(dstfd, srcfd); err != nil {
  185. return err
  186. }
  187. if srcinfo, err = os.Stat(src); err != nil {
  188. return err
  189. }
  190. return os.Chmod(dst, srcinfo.Mode())
  191. }
  192. /**
  193. * @description:
  194. * @param {*} src
  195. * @param {*} dst
  196. * @param {string} style
  197. * @return {*}
  198. * @method:
  199. * @router:
  200. */
  201. func CopySingleFile(src, dst, style string) error {
  202. var err error
  203. var srcfd *os.File
  204. var dstfd *os.File
  205. var srcinfo os.FileInfo
  206. if Exists(dst) {
  207. if style == "skip" {
  208. return nil
  209. } else {
  210. os.Remove(dst)
  211. }
  212. }
  213. if srcfd, err = os.Open(src); err != nil {
  214. return err
  215. }
  216. defer srcfd.Close()
  217. if dstfd, err = os.Create(dst); err != nil {
  218. return err
  219. }
  220. defer dstfd.Close()
  221. if _, err = io.Copy(dstfd, srcfd); err != nil {
  222. return err
  223. }
  224. if srcinfo, err = os.Stat(src); err != nil {
  225. return err
  226. }
  227. return os.Chmod(dst, srcinfo.Mode())
  228. }
  229. // Check for duplicate file names
  230. func GetNoDuplicateFileName(fullPath string) string {
  231. path, fileName := filepath.Split(fullPath)
  232. fileSuffix := path2.Ext(fileName)
  233. filenameOnly := strings.TrimSuffix(fileName, fileSuffix)
  234. for i := 0; Exists(fullPath); i++ {
  235. fullPath = path2.Join(path, filenameOnly+"("+strconv.Itoa(i+1)+")"+fileSuffix)
  236. }
  237. return fullPath
  238. }
  239. // Dir copies a whole directory recursively
  240. func CopyDir(src string, dst string, style string) error {
  241. var err error
  242. var fds []os.FileInfo
  243. var srcinfo os.FileInfo
  244. if srcinfo, err = os.Stat(src); err != nil {
  245. return err
  246. }
  247. if !srcinfo.IsDir() {
  248. if err = CopyFile(src, dst, style); err != nil {
  249. fmt.Println(err)
  250. }
  251. return nil
  252. }
  253. // dstPath := dst
  254. lastPath := src[strings.LastIndex(src, "/")+1:]
  255. dst += "/" + lastPath
  256. // for i := 0; Exists(dst); i++ {
  257. // dst = dstPath + "/" + lastPath + strconv.Itoa(i+1)
  258. // }
  259. if Exists(dst) {
  260. if style == "skip" {
  261. return nil
  262. } else {
  263. os.Remove(dst)
  264. }
  265. }
  266. if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
  267. return err
  268. }
  269. if fds, err = ioutil.ReadDir(src); err != nil {
  270. return err
  271. }
  272. for _, fd := range fds {
  273. srcfp := path.Join(src, fd.Name())
  274. dstfp := dst // path.Join(dst, fd.Name())
  275. if fd.IsDir() {
  276. if err = CopyDir(srcfp, dstfp, style); err != nil {
  277. fmt.Println(err)
  278. }
  279. } else {
  280. if err = CopyFile(srcfp, dstfp, style); err != nil {
  281. fmt.Println(err)
  282. }
  283. }
  284. }
  285. return nil
  286. }
  287. func WriteToPath(data []byte, path, name string) error {
  288. fullPath := path
  289. if strings.HasSuffix(path, "/") {
  290. fullPath += name
  291. } else {
  292. fullPath += "/" + name
  293. }
  294. return WriteToFullPath(data, fullPath, 0o666)
  295. }
  296. func WriteToFullPath(data []byte, fullPath string, perm fs.FileMode) error {
  297. if err := IsNotExistCreateFile(fullPath); err != nil {
  298. return err
  299. }
  300. file, err := os.OpenFile(fullPath,
  301. os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
  302. perm,
  303. )
  304. if err != nil {
  305. return err
  306. }
  307. defer file.Close()
  308. _, err = file.Write(data)
  309. return err
  310. }
  311. // 最终拼接
  312. func SpliceFiles(dir, path string, length int, startPoint int) error {
  313. fullPath := path
  314. if err := IsNotExistCreateFile(fullPath); err != nil {
  315. return err
  316. }
  317. file, _ := os.OpenFile(fullPath,
  318. os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
  319. 0o666,
  320. )
  321. defer file.Close()
  322. bufferedWriter := bufio.NewWriter(file)
  323. // todo: here should have a goroutine to remove each partial file after it is read, to save disk space
  324. for i := 0; i < length+startPoint-1; i++ {
  325. data, err := ioutil.ReadFile(dir + "/" + strconv.Itoa(i+startPoint))
  326. if err != nil {
  327. return err
  328. }
  329. if _, err := bufferedWriter.Write(data); err != nil { // recommend to use https://github.com/iceber/iouring-go for faster write
  330. return err
  331. }
  332. }
  333. bufferedWriter.Flush()
  334. return nil
  335. }
  336. func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
  337. switch t {
  338. case "zip", "":
  339. return ".zip", archiver.NewZip(), nil
  340. case "tar":
  341. return ".tar", archiver.NewTar(), nil
  342. case "targz":
  343. return ".tar.gz", archiver.NewTarGz(), nil
  344. case "tarbz2":
  345. return ".tar.bz2", archiver.NewTarBz2(), nil
  346. case "tarxz":
  347. return ".tar.xz", archiver.NewTarXz(), nil
  348. case "tarlz4":
  349. return ".tar.lz4", archiver.NewTarLz4(), nil
  350. case "tarsz":
  351. return ".tar.sz", archiver.NewTarSz(), nil
  352. default:
  353. return "", nil, errors.New("format not implemented")
  354. }
  355. }
  356. func AddFile(ar archiver.Writer, path, commonPath string) error {
  357. info, err := os.Stat(path)
  358. if err != nil {
  359. return err
  360. }
  361. if !info.IsDir() && !info.Mode().IsRegular() {
  362. return nil
  363. }
  364. file, err := os.Open(path)
  365. if err != nil {
  366. return err
  367. }
  368. defer file.Close()
  369. if path != commonPath {
  370. filename := info.Name()
  371. err = ar.Write(archiver.File{
  372. FileInfo: archiver.FileInfo{
  373. FileInfo: info,
  374. CustomName: filename,
  375. },
  376. ReadCloser: file,
  377. })
  378. if err != nil {
  379. return err
  380. }
  381. }
  382. if info.IsDir() {
  383. names, err := file.Readdirnames(0)
  384. if err != nil {
  385. return err
  386. }
  387. for _, name := range names {
  388. err = AddFile(ar, filepath.Join(path, name), commonPath)
  389. if err != nil {
  390. log.Printf("Failed to archive %v", err)
  391. }
  392. }
  393. }
  394. return nil
  395. }
  396. func CommonPrefix(sep byte, paths ...string) string {
  397. // Handle special cases.
  398. switch len(paths) {
  399. case 0:
  400. return ""
  401. case 1:
  402. return path.Clean(paths[0])
  403. }
  404. // Note, we treat string as []byte, not []rune as is often
  405. // done in Go. (And sep as byte, not rune). This is because
  406. // most/all supported OS' treat paths as string of non-zero
  407. // bytes. A filename may be displayed as a sequence of Unicode
  408. // runes (typically encoded as UTF-8) but paths are
  409. // not required to be valid UTF-8 or in any normalized form
  410. // (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
  411. // file names.
  412. c := []byte(path.Clean(paths[0]))
  413. // We add a trailing sep to handle the case where the
  414. // common prefix directory is included in the path list
  415. // (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
  416. // path.Clean will have cleaned off trailing / separators with
  417. // the exception of the root directory, "/" (in which case we
  418. // make it "//", but this will get fixed up to "/" bellow).
  419. c = append(c, sep)
  420. // Ignore the first path since it's already in c
  421. for _, v := range paths[1:] {
  422. // Clean up each path before testing it
  423. v = path.Clean(v) + string(sep)
  424. // Find the first non-common byte and truncate c
  425. if len(v) < len(c) {
  426. c = c[:len(v)]
  427. }
  428. for i := 0; i < len(c); i++ {
  429. if v[i] != c[i] {
  430. c = c[:i]
  431. break
  432. }
  433. }
  434. }
  435. // Remove trailing non-separator characters and the final separator
  436. for i := len(c) - 1; i >= 0; i-- {
  437. if c[i] == sep {
  438. c = c[:i]
  439. break
  440. }
  441. }
  442. return string(c)
  443. }
  444. func GetFileOrDirSize(path string) (int64, error) {
  445. fileInfo, err := os.Stat(path)
  446. if err != nil {
  447. return 0, err
  448. }
  449. if fileInfo.IsDir() {
  450. return DirSizeB(path + "/")
  451. }
  452. return fileInfo.Size(), nil
  453. }
  454. // getFileSize get file size by path(B)
  455. func DirSizeB(path string) (int64, error) {
  456. var size int64
  457. err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
  458. if !info.IsDir() {
  459. size += info.Size()
  460. }
  461. return err
  462. })
  463. return size, err
  464. }
  465. func MoveFile(sourcePath, destPath string) error {
  466. inputFile, err := os.Open(sourcePath)
  467. if err != nil {
  468. return fmt.Errorf("Couldn't open source file: %s", err)
  469. }
  470. outputFile, err := os.Create(destPath)
  471. if err != nil {
  472. inputFile.Close()
  473. return fmt.Errorf("Couldn't open dest file: %s", err)
  474. }
  475. defer outputFile.Close()
  476. _, err = io.Copy(outputFile, inputFile)
  477. inputFile.Close()
  478. if err != nil {
  479. return fmt.Errorf("Writing to output file failed: %s", err)
  480. }
  481. err = os.Remove(sourcePath)
  482. if err != nil {
  483. return fmt.Errorf("Failed removing original file: %s", err)
  484. }
  485. return nil
  486. }
  487. func ReadLine(lineNumber int, path string) string {
  488. file, err := os.Open(path)
  489. if err != nil {
  490. return ""
  491. }
  492. fileScanner := bufio.NewScanner(file)
  493. lineCount := 1
  494. for fileScanner.Scan() {
  495. if lineCount == lineNumber {
  496. return fileScanner.Text()
  497. }
  498. lineCount++
  499. }
  500. defer file.Close()
  501. return ""
  502. }
  503. func NameAccumulation(name string, dir string) string {
  504. path := filepath.Join(dir, name)
  505. if _, err := os.Stat(path); os.IsNotExist(err) {
  506. return name
  507. }
  508. base := name
  509. strings.Split(base, "_")
  510. index := strings.LastIndex(base, "_")
  511. if index < 0 {
  512. index = len(base)
  513. }
  514. for i := 1; ; i++ {
  515. newPath := filepath.Join(dir, fmt.Sprintf("%s_%d", base[:index], i))
  516. if _, err := os.Stat(newPath); os.IsNotExist(err) {
  517. return fmt.Sprintf("%s_%d", base[:index], i)
  518. }
  519. }
  520. }
  521. // / 解析多个文件上传中,每个具体的文件的信息
  522. // type FileHeader struct {
  523. // ContentDisposition string
  524. // Name string
  525. // FileName string
  526. // ///< 文件名
  527. // ContentType string
  528. // ContentLength int64
  529. // }
  530. // / 解析描述文件信息的头部
  531. // / @return FileHeader 文件名等信息的结构体
  532. // / @return bool 解析成功还是失败
  533. func ParseFileHeader(h []byte, boundary []byte) (map[string]string, bool) {
  534. arr := bytes.Split(h, boundary)
  535. //var out_header FileHeader
  536. //out_header.ContentLength = -1
  537. const (
  538. CONTENT_DISPOSITION = "Content-Disposition: "
  539. NAME = "name=\""
  540. FILENAME = "filename=\""
  541. CONTENT_TYPE = "Content-Type: "
  542. CONTENT_LENGTH = "Content-Length: "
  543. )
  544. result := make(map[string]string)
  545. for _, item := range arr {
  546. tarr := bytes.Split(item, []byte(";"))
  547. if len(tarr) != 2 {
  548. continue
  549. }
  550. tbyte := tarr[1]
  551. fmt.Println(string(tbyte))
  552. tbyte = bytes.ReplaceAll(tbyte, []byte("\r\n--"), []byte(""))
  553. tbyte = bytes.ReplaceAll(tbyte, []byte("name=\""), []byte(""))
  554. tempArr := bytes.Split(tbyte, []byte("\"\r\n\r\n"))
  555. if len(tempArr) != 2 {
  556. continue
  557. }
  558. bytes.HasPrefix(item, []byte("name="))
  559. result[strings.TrimSpace(string(tempArr[0]))] = strings.TrimSpace(string(tempArr[1]))
  560. }
  561. // for _, item := range arr {
  562. // if bytes.HasPrefix(item, []byte(CONTENT_DISPOSITION)) {
  563. // l := len(CONTENT_DISPOSITION)
  564. // arr1 := bytes.Split(item[l:], []byte("; "))
  565. // out_header.ContentDisposition = string(arr1[0])
  566. // if bytes.HasPrefix(arr1[1], []byte(NAME)) {
  567. // out_header.Name = string(arr1[1][len(NAME) : len(arr1[1])-1])
  568. // }
  569. // l = len(arr1[2])
  570. // if bytes.HasPrefix(arr1[2], []byte(FILENAME)) && arr1[2][l-1] == 0x22 {
  571. // out_header.FileName = string(arr1[2][len(FILENAME) : l-1])
  572. // }
  573. // } else if bytes.HasPrefix(item, []byte(CONTENT_TYPE)) {
  574. // l := len(CONTENT_TYPE)
  575. // out_header.ContentType = string(item[l:])
  576. // } else if bytes.HasPrefix(item, []byte(CONTENT_LENGTH)) {
  577. // l := len(CONTENT_LENGTH)
  578. // s := string(item[l:])
  579. // content_length, err := strconv.ParseInt(s, 10, 64)
  580. // if err != nil {
  581. // log.Printf("content length error:%s", string(item))
  582. // return out_header, false
  583. // } else {
  584. // out_header.ContentLength = content_length
  585. // }
  586. // } else {
  587. // log.Printf("unknown:%s\n", string(item))
  588. // }
  589. // }
  590. //fmt.Println(result)
  591. // if len(out_header.FileName) == 0 {
  592. // return out_header, false
  593. // }
  594. return result, true
  595. }
  596. // / 从流中一直读到文件的末位
  597. // / @return []byte 没有写到文件且又属于下一个文件的数据
  598. // / @return bool 是否已经读到流的末位了
  599. // / @return error 是否发生错误
  600. func ReadToBoundary(boundary []byte, stream io.ReadCloser, target io.WriteCloser) ([]byte, bool, error) {
  601. read_data := make([]byte, 1024*8)
  602. read_data_len := 0
  603. buf := make([]byte, 1024*4)
  604. b_len := len(boundary)
  605. reach_end := false
  606. for !reach_end {
  607. read_len, err := stream.Read(buf)
  608. if err != nil {
  609. if err != io.EOF && read_len <= 0 {
  610. return nil, true, err
  611. }
  612. reach_end = true
  613. }
  614. //todo: 下面这一句很蠢,值得优化
  615. copy(read_data[read_data_len:], buf[:read_len]) //追加到另一块buffer,仅仅只是为了搜索方便
  616. read_data_len += read_len
  617. if read_data_len < b_len+4 {
  618. continue
  619. }
  620. loc := bytes.Index(read_data[:read_data_len], boundary)
  621. if loc >= 0 {
  622. //找到了结束位置
  623. target.Write(read_data[:loc-4])
  624. return read_data[loc:read_data_len], reach_end, nil
  625. }
  626. target.Write(read_data[:read_data_len-b_len-4])
  627. copy(read_data[0:], read_data[read_data_len-b_len-4:])
  628. read_data_len = b_len + 4
  629. }
  630. target.Write(read_data[:read_data_len])
  631. return nil, reach_end, nil
  632. }
  633. // / 解析表单的头部
  634. // / @param read_data 已经从流中读到的数据
  635. // / @param read_total 已经从流中读到的数据长度
  636. // / @param boundary 表单的分割字符串
  637. // / @param stream 输入流
  638. // / @return FileHeader 文件名等信息头
  639. // /[]byte 已经从流中读到的部分
  640. // /error 是否发生错误
  641. func ParseFromHead(read_data []byte, read_total int, boundary []byte, stream io.ReadCloser) (map[string]string, []byte, error) {
  642. buf := make([]byte, 1024*8)
  643. found_boundary := false
  644. boundary_loc := -1
  645. for {
  646. read_len, err := stream.Read(buf)
  647. if err != nil {
  648. if err != io.EOF {
  649. return nil, nil, err
  650. }
  651. break
  652. }
  653. if read_total+read_len > cap(read_data) {
  654. return nil, nil, fmt.Errorf("not found boundary")
  655. }
  656. copy(read_data[read_total:], buf[:read_len])
  657. read_total += read_len
  658. if !found_boundary {
  659. boundary_loc = bytes.LastIndex(read_data[:read_total], boundary)
  660. if boundary_loc == -1 {
  661. continue
  662. }
  663. found_boundary = true
  664. }
  665. start_loc := boundary_loc + len(boundary)
  666. fmt.Println(string(read_data))
  667. file_head_loc := bytes.Index(read_data[start_loc:read_total], []byte("\r\n\r\n"))
  668. if file_head_loc == -1 {
  669. continue
  670. }
  671. file_head_loc += start_loc
  672. ret := false
  673. headMap, ret := ParseFileHeader(read_data, boundary)
  674. if !ret {
  675. return headMap, nil, fmt.Errorf("ParseFileHeader fail:%s", string(read_data[start_loc:file_head_loc]))
  676. }
  677. return headMap, read_data[file_head_loc+4 : read_total], nil
  678. }
  679. return nil, nil, fmt.Errorf("reach to sream EOF")
  680. }