data.GetCSV
假設有以下目錄結構:
my-project/
└── other-files/
└── pets.csv
可使用下列任一方式來存取資料:
{{ $data := getCSV "," "other-files/pets.csv" }}
{{ $data := getCSV "," "other-files/" "pets.csv" }}
存取遠端資料可使用下列任一方式:
{{ $data := getCSV "," "https://example.org/pets.csv" }}
{{ $data := getCSV "," "https://example.org/" "pets.csv" }}
結果資料結構為二維陣列:
[
["name","type","breed","age"],
["Spot","dog","Collie","3"],
["Felix","cat","Malicious","7"]
]
選項
提供選項映射來新增請求標頭:
{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
使用切片新增多個標頭:
{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
全域資源替代方法
存取全域資源時,建議使用 resources.Get
函式搭配 transform.Unmarshal
。
my-project/
└── assets/
└── data/
└── pets.csv
{{ $data := dict }}
{{ $p := "data/pets.csv" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "無法取得資源 %q" $p }}
{{ end }}
頁面資源替代方法
存取頁面資源時,建議使用 Resources.Get
方法搭配 transform.Unmarshal
。
my-project/
└── content/
└── posts/
└── my-pets/
├── index.md
└── pets.csv
{{ $data := dict }}
{{ $p := "pets.csv" }}
{{ with .Resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "無法取得資源 %q" $p }}
{{ end }}
遠端資源替代方法
存取遠端資源時,建議使用 resources.GetRemote
函式搭配 transform.Unmarshal
,以改善錯誤處理和快取控制。
{{ $data := dict }}
{{ $u := "https://example.org/pets.csv" }}
{{ with resources.GetRemote $u }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ end }}
{{ else }}
{{ errorf "無法取得遠端資源 %q" $u }}
{{ end }}