在浏览器中执行的Golang函数中读取CSV文件
我已经在Golang上写了一个脚本,以对存储在CSV中的用户故事进行排序,并以固定的团队速度创建冲刺。 以下是与读取CSV文件有关的部分。
// userstory.go
f, err := os.Open("userstories.csv")
if err != nil {
log.Fatal(err)
} the file at the end of the program
defer f.Close()
csvReader := csv.NewReader(f)
data, err := csvReader.ReadAll()
现在,由于i 旨在使其在浏览器中起作用(没有后端),并且Golang代码已编译为WASM,所以我不能再使用OS文件了。
因此,我正在尝试以获取文件并将其作为 uint8array
参数(从javaScript)到函数 getsprints
:
// js code
const runScript = async () => {
let files = data.fileList;
files[0].arrayBuffer().then((x) => {
var b = new Uint8Array(x);
console.log(b)
console.log(GetSprints(b));
})
}
getsprints
已接触到JavaScript,并带有以下 js.global()。set
:
// userstory.go
func main() {
fmt.Println("Go WebAssembly: loaded UserStory.go")
js.Global().Set("GetSprints", getSprintsWrapper())
<-make(chan bool)
}
uint8array
以第一个参数传递,被复制到 [] byte
buffer:
// userstory.go
func getSprintsWrapper() js.Func {
getSprintsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var dst []byte
js.CopyBytesToGo(dst, args[0])
return GetSprints(dst)
})
return getSprintsFunc
}
给定 csv.newreader 接受a io.reader 作为参数,我尝试用 bytes.reader ,
// userstory.go
func GetSprints(inputFile []byte) []Sprint {
f := bytes.NewReader(inputFile)
csvReader := csv.NewReader(f)
data, err := csvReader.ReadAll()
if err != nil {
log.Fatal(err)
}
fmt.Println("No errors reading csv. Data: ", data)
// ...
}
其他对用Golang代码解析文件的人感兴趣的人?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以用 arraybuffer()方法“> text()。
方法 text() “返回” (允许我术语,但它返回a promise )一个表示文件内容的UTF-8字符串。
然后,在Golang侧,在传递字符串之前,我将其转换为
[]字节
,
getSprints
最终能够处理CSV。上添加了JSON.PARSE调用,
编辑:在Golang侧的JS和JSON.MARSHAL
因此现在可以将结果处理为JavaScript对象。
如果有人有任何改进建议,请告诉我。谢谢
It worked replacing the arrayBuffer() method with text().
The method text() "returns" (allow me the term but it returns a Promise) a UTF-8 string representing the content of the file.
Then on the golang side, before passing the string, I converted it to
[]byte
and the
GetSprints
is finally able to process the csv.Edit: Added a JSON.parse call on the js
and json.Marshal on golang side
so now the results can be handled as javascript objects.

If anyone has any suggestions to improve it, please let me know. Thank you