Golang飞返文件

问题描述

我有ECHO框架,该框架应应要求返回文件,并且运行良好

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")
}

但是问题是,是否可以不创建物理文件export.ini,之后再不删除它?可能以某种方式即时返回内容? 谢谢

解决方法

我认为您需要Send Blob

发送Blob 上下文#Blob(代码int,contentType字符串,b []字节)可以是 用于发送具有提供的内容类型的任意数据响应,并且 状态代码。

示例

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)
}

您可以使用WriteTo函数将cfg内容首先写入io.Writer,然后可以使用那些内容代替data(在前面的代码示例中) 。还请确保将内容类型更改为text/plain