我需要請求、處理資料並將其格式化為 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
到目前為止一切順利 - 現在我想透過
刪除中間文件我還是不太明白如何使用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中文網其他相關文章!