问题描述
我正在使用gin-gonic在golang中创建一个HTTP REST服务器
我的代码是:
func main() {
var port string
if len(os.Args) == 1 {
port = "8080"
} else {
port = os.Args[1]
}
router := gin.Default()
router.GET("/:a/*b",func(c *gin.Context) {
// My custom code to get "download" reader from some third party cloud storage.
// Create the file at the server side
out,err := os.Create(b)
if err != nil {
c.String(http.StatusInternalServerError,"Error in file creation at server side\n")
return
}
c.String(http.StatusOK,"File created at server side\n")
_,err = io.copy(out,download)
if err != nil {
c.String(http.StatusInternalServerError,"Some error occured while downloading the object\n")
return
}
// Close the file at the server side
err = out.Close()
if err != nil {
c.String(http.StatusInternalServerError,"Some error occured while closing the file at server side\n")
}
// Download the file from server side at client side
c.String(http.StatusOK,"Downloading the file at client side\n")
c.FileAttachment(objectPath,objectPath)
c.String(http.StatusOK,"\nFile downlaoded at the client side successfully\n")
c.String(http.StatusOK,"Object downloaded successfully\n")
})
// Listen and serve
router.Run(":"+port)
}
当我在客户端命令提示符下运行curl命令时,它会将文件下载到我的REST服务器上,但没有在客户端上下载。但是,gin-gonic godoc说:
功能(* Context)文件
func (c *Context) File(filepath string)
File以一种有效的方式将指定的文件写入主体流。
func(* Context)FileAttachmentfunc (c *Context) FileAttachment(filepath,filename string)
FileAttachment以一种有效的方式将指定的文件写入主体流中。在客户端,通常将使用给定的文件名下载文件
功能(* Context)FileFromFSfunc (c *Context) FileFromFS(filepath string,fs http.FileSystem)
FileFromFS以一种有效的方式将来自http.FileSystem的指定文件写入主体流。
但是,从命令提示符输出中仔细观察,它打印了txt文件的内容,我需要将其保存在客户端上
因此,我想通过我的自定义REST API服务器将从第三方存储区下载的内容流式传输到客户端命令提示符或浏览器。
我在这里想念东西吗?
谢谢
更新:我尝试编写Content-disposition
和Content-Type
标头来响应,如下所示:
package main
import (
"context"
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func main() {
var port string
if len(os.Args) == 1 {
port = "8080"
} else {
port = os.Args[1]
}
router := gin.Default()
router.GET("/:a/*b",func(c *gin.Context) {
param_a := c.Param("a")
param_b := c.Param("b")
reqToken := c.GetHeader("my_custom_key")
// My custom code to get "download" reader from some third party cloud storage.
c.String(http.StatusOK,"Downloading the object\n")
c.Writer.Header().Add("Content-disposition",fmt.Sprintf("attachment; filename=%",param_b))
c.Writer.Header().Add("Content-Type",c.GetHeader("Content-Type"))
c.File(param_b)
c.String(http.StatusOK,"Object downloaded successfully\n")
err = download.Close()
if err != nil {
c.String(http.StatusInternalServerError,"Error in closing the download of the object\n")
return
}
c.String(http.StatusOK,"Object downloaded completed & closed successfully\n")
})
// Listen and serve
router.Run(":"+port)
}
现在,它显示错误,并显示以下成功消息,但仍然没有在客户端下载填充:
404 page not found
Object downloaded successfully
Object downloaded completed & closed successfully
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)