英文:
Idiomatic conversion of []map[string]string to csv []byte
问题
我有一个方法,接受一个io.Reader来进行HTTP POST请求(如果需要,我可以进行更改)。我将以x行的批次提交给这个调用方法。为了方便检查键是否正确,我将我的行存储为map[string]string。如何以最简化的方式将map[string]string的切片提交给当前接受io.Reader的调用方法?
英文:
I have a method which accepts an io.Reader in order to make an http POST (I can change this if needed) I will be submitted batches of x rows to this call method. I'm storing my rows as map[string]string for ease of checking that the keys are correct. What is the most streamlined way to submit a slice of map[string]string to that call method, which currently accepts a io.Reader?
答案1
得分: 3
使用encoding/csv包来生成CSV编码。以下是如何根据列名将其编码为[]byte的示例代码:
func encodeCSV(columns []string, rows []map[string]string) ([]byte, error) {
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(columns); err != nil {
return nil, err
}
r := make([]string, len(columns))
for _, row := range rows {
for i, column := range columns {
r[i] = row[column]
}
if err := w.Write(r); err != nil {
return nil, err
}
}
if err := w.Flush(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
使用bytes.NewReader创建POST请求的请求体:
data, err := encodeCSV(columns, rows)
if err != nil {
// 处理错误
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
如果你对数据格式有控制权,可以考虑使用JSON:
data, err := json.Marshal(rows)
if err != nil {
// 处理错误
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
英文:
Use the encoding/csv package to generate the CSV encoding. Here's how to encode to a []byte given column names:
func encodeCSV(columns []string, rows []map[string]string) ([]byte, error) {
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(columns); err != nil {
return nil, err
}
r := make([]string, len(columns))
for _, row := range rows {
for i, column := range columns {
r[i] = row[column]
}
if err := w.Write(r); err != nil {
return nil, err
}
}
if err := w.Flush(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
Use bytes.NewReader to create the body for post:
data, err := encodeCSV(coluns, rows)
if err != nil {
// handle error
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
If you have control over the data format, then consider using JSON:
data, err := json.Marshal(rows)
if err != nil {
// handle error
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论