在進行網頁開發中,經常需要使用 HTTP 請求來傳輸資料。在某些情況下,我們可能需要將請求的內容類型設定為 multipart/form-data,並在客戶端取得 Content-Type 為 text/plain 的資料。這樣的設定可以透過在 HTTP 伺服器的標頭中進行設定來實現。在 PHP 中,我們可以透過對應的函數和方法來實現這個目標。在本文中,php小編西瓜將為您介紹如何在 PHP 中設定 HTTP 伺服器的標頭內容類型為 multipart/form-data,並在客戶端取得 Content-Type 為 text/plain 的資料。
問題內容
Go 伺服器將 header Content-type 設為 multipart/form-data
#router.HandleFunc("/certificates", serveFilesHandler).Methods("GET") func serveFilesHandler(w http.ResponseWriter, r *http.Request) { currentDir, err := os.Getwd() if err != nil { log.Fatal("Can not find the current directory: ", err) } pathToCertifs := "../certificates" // Create a multipart writer for the response multipartWriter := multipart.NewWriter(w) files := []string{"client.key", "server.key", "rootCA.key"} for _, filename := range files { filePath := filepath.Join(currentDir, pathToCertifs, filename) fmt.Println("see the filePath: ", filePath) // Open the file file, err := os.Open(filePath) if err != nil {} defer file.Close() // Create a new form file part part, err := multipartWriter.CreateFormFile("files", filename) if err != nil {} // Copy the file content to the part _, err = io.Copy(part, file) if err != nil {} } // Set the content type for the response w.Header().Set("Content-Type", multipartWriter.FormDataContentType()) fmt.Println("Content-Type set to:", w.Header().Get("Content-Type")) // printout Content-Type set to: multipart/form-data; boundary=7b326 // Close the multipart writer multipartWriter.Close() }
但是在客戶端我得到了
Expected multipart response, but received: text/plain; charset=utf-8
但是有效負載位於主體中
body, err := ioutil.ReadAll(resp.Body) if err != nil {} Content-Type: text/plain; charset=utf-8 Response Body: --aee406774ba6a054d52e39a3cdb72f42d32bd30828adbfb1982d278cab56 Content-Disposition: form-data; name="files"; filename="client.key" Content-Type: application/octet-stream -----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNg4ZaTLC/GdLK xzFDIyPlYyKs/hUXpPkZAQk+3gnvmBaDuMNq2jd2nQoQohmk1zIuD8oj9se5L+3P
但我無法按部分獲取它,因為內容類型不是 multipart/form-data,所以這不起作用
multipartReader := multipart.NewReader(resp.Body, boundaryFromContentType(contentType)) // Read each part for { part, err := multipartReader.NextPart() if err != nil { break } defer part.Close() ......
我缺少什麼,謝謝?
ps:這個問題需要更多細節,我覺得已經很清楚了,所以我添加了這一行,之後可能會起作用。
解決方法
在將任何內容寫入回應正文之前,必須設定 HTTP 回應標頭。一旦提交了標頭(當您寫入內容到回應正文時),您就無法設定或變更標頭。
您建立多部分編寫器以及所有部分和內容,然後設定回應標頭,然後僅關閉多部分編寫器。關閉只是為了完成多部分訊息並寫入尾部邊界,但其許多內容可能已經被寫入並提交。
在向多部分編寫器新增/寫入任何內容之前移動設定標頭:
// Create a multipart writer for the response multipartWriter := multipart.NewWriter(w) w.Header().Set("Content-Type", multipartWriter.FormDataContentType()) // Now proceed to add files...
以上是go http 伺服器標頭內容類型設定為 multipart/form-data 但在客戶端取得 Content-Type: text/plain的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

在Go語言中,接口的實現是通過隱式的方式進行的。 1)隱式實現:類型只要包含接口定義的所有方法,就自動滿足該接口。 2)空接口:interface{}類型所有類型都實現,適度使用可避免類型安全問題。 3)接口隔離:設計小而專注的接口,提高代碼的可維護性和重用性。 4)測試:接口有助於通過模擬依賴進行單元測試。 5)錯誤處理:通過接口可以統一處理錯誤。

go'sinterfacesareimpliclyimplyed,與Javaandc#wheRequireexplitiCimplation.1)Ingo,AnyTypeWithTheRequiredMethodSautSautSautautapitymethodimimplementsaninternionsaninterninternionsaninterface.2)

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!