
我试图通过创建 POST 请求并将其发送到不同的服务器。在我的过程中,我尝试发送 3 个 POST,一个发送到第一台服务器,其余发送到另一台服务器。 p>
但是它只适用于第一个 POST 请求,其余请求得到 200 代码,但文件仍然是空的。我不熟悉 http 连接,我该如何纠正我的程序? 如果您能帮助我,我将不胜感激!
这是接收文件的函数。
func ReceivePublicKey() *gin.Engine {
router := gin.Default()
router.MaxMultipartMemory = 8 << 20
//router.Static("/", "./static")
router.POST("/receive", func(context *gin.Context) {
file, _ := context.FormFile("file")
log.Println(file.Filename)
dst := "./" + file.Filename
context.SaveUploadedFile(file, dst)
context.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
context.String(200, "server: receive publicKey successfully!")
})
return router
}这是创建和发送请求的函数
篇文章是针对git版本控制和工作流的总结,如果有些朋友之前还没使用过git,对git的基本概念和命令不是很熟悉,可以从以下基本教程入手: Git是分布式版本控制系统,与SVN类似的集中化版本控制系统相比,集中化版本控制系统虽然能够令多个团队成员一起协作开发,但有时如果中央服务器宕机的话,谁也无法在宕机期间提交更新和协同开发。甚至有时,中央服务器磁盘故障,恰巧又没有做备份或备份没及时,那就可能有丢失数据的风险。感兴趣的朋友可以过来看看
0
func CreateSendFileReq(file *os.File, fileName string, url string) *http.Request {
bodyBuf := &bytes.Buffer{}
bodyWrite := multipart.NewWriter(bodyBuf)
fileWrite, err := bodyWrite.CreateFormFile("file", fileName)
_, err = io.Copy(fileWrite, file)
if err != nil {
log.Println("err")
}
bodyWrite.Close()
if err != nil {
log.Println("err")
}
req, _ := http.NewRequest("POST", url, bodyBuf)
req.Header.Set("Content-Type", bodyWrite.FormDataContentType())
return req
}
func SendRequest(r *http.Request) *http.Response {
client := &http.Client{}
resp, err := client.Do(r)
if err == nil {
return resp
} else {
log.Fatal(err)
return nil
}
}还有不起作用的功能
func IotInit() {
privateFile, _ := os.Open("private.pem")
publicFile, _ := os.Open("public.pem")
userId := GenerateIotId(publicFile)
fmt.Println(userId)
sendPrivateToServer := Controller.CreateSendFileReq(privateFile, userId+".pem", "http://192.168.42.129:8090/receive")
sendPublicToUser := Controller.CreateSendFileReq(publicFile, "public.pem", "http://localhost:8090/receive")
resp := Controller.SendRequest(sendPublicToUser)
if resp.StatusCode != 200 {
log.Fatal(resp.StatusCode)
}
resp.Body.Close()
sendPrivateToUser := Controller.CreateSendFileReq(privateFile, "private.pem", "http://localhost:8090/receive")
resp = Controller.SendRequest(sendPrivateToServer)
if resp.StatusCode != 200 {
log.Fatal(resp.StatusCode)
}
resp.Body.Close()
resp = Controller.SendRequest(sendPrivateToUser)
if resp.StatusCode != 200 {
log.Fatal(resp.StatusCode)
}
resp.Body.Close()
publicFile.Close()
privateFile.Close()
}好吧,现在我发现了我的错误。 首先,我没有检查文件的大小,这解释了为什么我在保存空文件时得到 200 代码。 第二个在 IotInit() 中获取 userId 我使用了 io.Copy() 并使文件指针指向文件结尾,这解释了为什么“public.pem”为空,我永远不要将任何内容复制到请求体。此外,我在创建 POST 请求时使用 io.Copy(),“private.pem”也可能为空。
以上就是使用 gin 时如何将文件发送到一个进程中的不同服务器?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号