Golang return file from fly

1.2k Views Asked by At

I have the ECHO framework which should return the file on request, and it's working well

func IniExport(c echo.Context) error{
    cfg := ini.Empty()
    if section, err := cfg.NewSection("test_section"); err != nil {
        return c.JSON(http.StatusInternalServerError, "Problems with generation of export file.")
    }
    if key, err := cfg.Section("test_section").NewKey("name", "value"); err != nil {
        return c.JSON(http.StatusInternalServerError, "Problems with generation of export file.")
    }
    cfg.SaveTo("export.ini")
    defer os.Remove("export.ini")
    return c.Attachment("export.ini", "export.ini")
}

But question, is it possible to not create physical file export.ini and after do not remove it? Possible to return content on the fly somehow? Thanks

1

There are 1 best solutions below

0
On

I think you need Send Blob.

Send Blob Context#Blob(code int, contentType string, b []byte) can be used to send an arbitrary data response with provided content type and status code.

Example

func(c echo.Context) (err error) {
  data := []byte(`0306703,0035866,NO_ACTION,06/19/2006
      0086003,"0005866",UPDATED,06/19/2006`)
    return c.Blob(http.StatusOK, "text/csv", data)
}

You can use the WriteTo function to write the cfg content to the io.Writer first and then those contents can be used instead of data(in the previous code example. Also make sure to change the content type to text/plain)