0

I'm coding in Go, and I created a file handler and a program that prints the value of that file.

However, the file that should be created with file.Filename is deleted when I run it.

I don't know what the reason is, even if I try to debug, the answer doesn't come out, and even if I google it, I don't get the answer.

(64bit windows 10 (WSL2))

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "os"

    "github.com/labstack/echo"
)

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func readFile(filename string) string {
    data, err := ioutil.ReadFile(filename)
    checkErr(err)
    return string(data)
}

func main() {
    e := echo.New()

    e.POST("/file", func(c echo.Context) error {
        file, err := c.FormFile("file")
        checkErr(err)

        src, err := file.Open()
        checkErr(err)
        defer src.Close()

        dst, err := os.Create(file.Filename)
        checkErr(err)
        defer dst.Close()

        _, err = io.Copy(dst, src)
        checkErr(err)

        data := readFile(file.Filename)

        fmt.Println(data)

        return c.String(200, "sd")
    })

    e.Logger.Fatal(e.Start(":5000"))
}

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
cdh88
  • 3
  • 4

1 Answers1

0

I'm guessing that your file exists, but the code that you wrote is reading the file before the changes are "flushed to disk".

Right here:

defer dst.Close()
 _, err = io.Copy(dst, src)

Should Close() or Sync() your writer as soon as possible, otherwise you may read before the write is finished. And since your readFile() function isn't re-using the file, you might as well just close (not Sync()) it immediately, not deferred

Try this:

 _, err = io.Copy(dst, src)
dst.Close()
if err != nil {
  
}

There could be an error while copying, but we still want to Close() the file (if there wasn't an error during the os.Create, os.Open, or os.OpenFile...

Dharman
  • 30,962
  • 25
  • 85
  • 135
aerth
  • 468
  • 4
  • 8