如何解决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
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。