Home > Software design >  Create and serve a file in Golang without saving it to the disk
Create and serve a file in Golang without saving it to the disk

Time:09-17

I want to use the data provided by the client to serve a file for them to download (say .txt) without creating or persisting any files on my server. How can I do it?

For instance, I want to omit the os.Create() defer f.Close() part from the following code with Gin framework:

func serveFile(c *gin.Context) {
    
    path := "/tmp/hello.txt"
    f, _ := os.Create(path)
    defer f.Close()

    f.WriteString("hello world")
    f.Sync()

    // ...
    c.File(path)
}

CodePudding user response:

Use c.Data() to write a string to the response:

c.Data(http.StatusOK, "text/plain", []byte("hello world"))

CodePudding user response:

After setting proper response headers eg

w.Header().Set("Content-Disposition", "attachment; filename=hello.txt")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))

you can

w.Write("hello world")

you can also use http.ServeContent

https://cs.opensource.google/go/go/ /refs/tags/go1.17.1:src/net/http/fs.go;l=192v

  • Related