我需要請求、處理資料並將其格式化為 csv,然後根據請求透過 web 服務發送它們。
假設請求和處理的資料位於下面的 data
中,我設法使用中間臨時檔案來做到這一點:
package main import ( "encoding/csv" "io/ioutil" "net/http" "os" "strconv" "github.com/go-chi/chi/v5" ) type data struct { name string age int } func main() { data := []data{ {"john", 30}, {"jane", 20}, } tempfilename := "temp.csv" // create temporary intermediate file file, err := os.create(tempfilename) defer file.close() if err != nil { panic(err) } w := csv.newwriter(file) var csvdata [][]string for _, record := range data { row := []string{record.name, strconv.itoa(record.age)} csvdata = append(csvdata, row) } w.writeall(csvdata) // read temporary intermediate file to send it via http filebytes, err := ioutil.readfile(tempfilename) if err != nil { panic(err) } // send the file on request router := chi.newrouter() router.get("/data", func(w http.responsewriter, r *http.request) { w.header().set("content-type", "application/octet-stream") w.writeheader(http.statusok) w.write(filebytes) }) http.listenandserve(":8087", router) }
請求成功:
PS C:\temp> wget http://localhost:8087/data --2023-06-13 15:34:00-- http://localhost:8087/data Resolving localhost (localhost)... ::1, 127.0.0.1 Connecting to localhost (localhost)|::1|:8087... connected. HTTP request sent, awaiting response... 200 OK Length: 16 [application/octet-stream] Saving to: 'data' data 100%[=================================================>] 16 --.-KB/s in 0s 2023-06-13 15:34:00 (523 KB/s) - 'data' saved [16/16] PS C:\temp> cat data John,30 Jane,20
到目前為止一切順利 - 現在我想透過
刪除中間文件- 使用記憶體「容器」來寫入 csv 資料
- 將其內容以位元組形式寫入 http 編寫器
我還是不太明白如何使用io.*
和bufio.*
來登陸所需的類型:
-
csv.newwriter()
需要*os.file
並傳回*csv.writer
- #這個
*csv.writer
內容需要以某種方式提取為byte
... - ...為了提供
http.responsewriter.write()
解決不同類型的記憶體檔案操作問題的一般機制(以及特定於本例的機制)是什麼?
正確答案
csv.newwriter
採用io.writer
,因此您可以將http.responsewriter
的實例傳遞給它,而無需將內容寫入檔案或記憶體。
這是示範:
package main import ( "encoding/csv" "fmt" "net/http" "strconv" "github.com/go-chi/chi/v5" ) type Data struct { Name string Age int } func main() { router := chi.NewRouter() router.Get("/data", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/octet-stream") w.WriteHeader(http.StatusOK) data := []Data{ {"John", 30}, {"Jane", 20}, } csvWriter := csv.NewWriter(w) var csvData [][]string for _, record := range data { row := []string{record.Name, strconv.Itoa(record.Age)} csvData = append(csvData, row) } if err := csvWriter.WriteAll(csvData); err != nil { // handle the error fmt.Println(err) } }) http.ListenAndServe(":8087", router) }
以上是如何寫入記憶體中的文件,然後透過 HTTP 發送它而不使用中間文件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

golang ...


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

禪工作室 13.0.1
強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器