卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34104本站已运行391

使用 gin 时如何将文件发送到一个进程中的不同服务器?

使用 gin 时如何将文件发送到一个进程中的不同服务器?

问题内容

我试图通过创建 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
}

这是创建和发送请求的函数

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”也可能为空。

卓越飞翔博客
上一篇: 在 go 中打印用户输入的字符串 n 次
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏