搜尋
首頁後端開發Golang使用 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」也可能為空。

以上是使用 gin 時如何將檔案傳送到一個進程中的不同伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在GO應用程序中有效記錄錯誤在GO應用程序中有效記錄錯誤Apr 30, 2025 am 12:23 AM

有效的Go應用錯誤日誌記錄需要平衡細節和性能。 1)使用標準log包簡單但缺乏上下文。 2)logrus提供結構化日誌和自定義字段。 3)zap結合性能和結構化日誌,但需要更多設置。完整的錯誤日誌系統應包括錯誤enrichment、日誌級別、集中式日誌、性能考慮和錯誤處理模式。

go中的空接口(接口{}):用例和注意事項go中的空接口(接口{}):用例和注意事項Apr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

比較並發模型:GO與其他語言比較並發模型:GO與其他語言Apr 30, 2025 am 12:20 AM

go'sconcurrencyModelisuniquedUetoItsuseofGoroutinesAndChannels,offeringAlightWeightandefficePappRockhiffcomparredTothread-likeLanguagesLikeLikeJjava,Python,andrust.1)

GO的並發模型:解釋的Goroutines和頻道GO的並發模型:解釋的Goroutines和頻道Apr 30, 2025 am 12:04 AM

go'sconcurrencyModeluessgoroutinesandChannelStomanageConconCurrentPrommmengement.1)GoroutinesArightweightThreadThreadSthAtalLeadSthAtalAlaLeasyParalleAftasks,增強Performance.2)ChannelsfacilitatesfacilitatesafeDataTaAexafeDataTaAexchangeBetnegnegoroutinesGoroutinesGoroutinesGoroutinesGoroutines,crucialforsforsynchrroniz

GO中的接口和多態性:實現代碼可重複使用性GO中的接口和多態性:實現代碼可重複使用性Apr 29, 2025 am 12:31 AM

Interfacesand -polymormormormormormingingoenhancecodereusanity和Maintainability.1)defineInterfaceSattherightabStractractionLevel.2)useInterInterFacesFordEffordExpentIndention.3)ProfileCodeTomeAgePerformancemacts。

'初始化”功能在GO中的作用是什麼?'初始化”功能在GO中的作用是什麼?Apr 29, 2025 am 12:28 AM

initiTfunctioningOrunSautomation beforeTheMainFunctionToInitializePackages andSetUptheNvironment.it'susefulforsettingupglobalvariables,資源和performingOne-timesEtepaskSarpaskSacraskSacrastAscacrAssanyPackage.here'shere'shere'shere'shere'shodshowitworks:1)Itcanbebeusedinanananainapthecate,NotjustAckAckAptocakeo

GO中的界面組成:構建複雜的抽象GO中的界面組成:構建複雜的抽象Apr 29, 2025 am 12:24 AM

接口組合在Go編程中通過將功能分解為小型、專注的接口來構建複雜抽象。 1)定義Reader、Writer和Closer接口。 2)通過組合這些接口創建如File和NetworkStream的複雜類型。 3)使用ProcessData函數展示如何處理這些組合接口。這種方法增強了代碼的靈活性、可測試性和可重用性,但需注意避免過度碎片化和組合複雜性。

在GO中使用Init功能時的潛在陷阱和考慮因素在GO中使用Init功能時的潛在陷阱和考慮因素Apr 29, 2025 am 12:02 AM

initfunctionsingoareAutomationalCalledBeLedBeForeTheMainFunctionandAreuseFulforSetupButcomeWithChallenges.1)executiondorder:totiernitFunctionSrunIndIndefinitionorder,cancancapationSifsUsiseSiftheyDepplothother.2)測試:sterfunctionsmunctionsmunctionsMayInterfionsMayInterferfereWithTests,b

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),