在浏览器中执行的Golang函数中读取CSV文件

发布于 2025-02-03 14:27:37 字数 2467 浏览 1 评论 0 原文

我已经在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代码解析文件的人感兴趣的人?

谢谢!

I have written a script in Golang to sort user stories stored in a csv and create sprints with a fixed team velocity.
The following is the part related to reading the csv file.

// 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()

Now, since I aim to make it work in the browser (with no backend) and the golang code is compiled to wasm, I can't use os files anymore.

So I'm trying to get the ArrayBuffer from the File and pass it as an Uint8Array argument (from JavaScript) to the function 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 has been exposed to JavaScript with the following js.Global().Set:

// userstory.go
func main() {
    fmt.Println("Go WebAssembly: loaded UserStory.go")
    js.Global().Set("GetSprints", getSprintsWrapper())
    <-make(chan bool)
}

and the Uint8Array passed as first argument, is copied to a []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
}

Given that csv.NewReader accepts a io.Reader as argument, i tried to replace the file descriptor with 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)
  // ...
}

but it results in an empty array.
enter image description here

Someone else interested in parsing files with golang code compiled to wasm?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别闹i 2025-02-10 14:27:37

它可以用 arraybuffer()方法“> text()

方法 text() “返回” (允许我术语,但它返回a promise )一个表示文件内容的UTF-8字符串。

// js code
const runScript = async () => {
  
  let files = data.fileList;    
  files[0].text().then((x) => {
    console.log(GetSprints(x));
  })
}

然后,在Golang侧,在传递字符串之前,我将其转换为 []字节

// userstory.go
func getSprintsWrapper() js.Func {
    getSprintsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        fmt.Println([]byte(args[0].String()))
        return GetSprints([]byte(args[0].String()))
    })
    return getSprintsFunc
}

getSprints 最终能够处理CSV。

// userstory.go
func GetSprints(inputFile []byte) []Sprint {
    f := bytes.NewReader(inputFile)
    csvReader := csv.NewReader(f)

    fmt.Println(csvReader.Read())
    data, err := csvReader.ReadAll()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("No errors reading csv. Data: ", data)


上添加了JSON.PARSE调用,

// js
files[0].text().then((x) => {
 var sprints = JSON.parse(GetSprints(x));
   console.log(sprints);
})

编辑:在Golang侧的JS和JSON.MARSHAL

// userstory.go
func getSprintsWrapper() js.Func {
    getSprintsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        b, err := json.Marshal(GetSprints([]byte(args[0].String())))
        if err != nil {
            fmt.Println(err)
        }
        return string(b)
    })
    return getSprintsFunc
}

因此现在可以将结果处理为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.

// js code
const runScript = async () => {
  
  let files = data.fileList;    
  files[0].text().then((x) => {
    console.log(GetSprints(x));
  })
}

Then on the golang side, before passing the string, I converted it to []byte

// userstory.go
func getSprintsWrapper() js.Func {
    getSprintsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        fmt.Println([]byte(args[0].String()))
        return GetSprints([]byte(args[0].String()))
    })
    return getSprintsFunc
}

and the GetSprints is finally able to process the csv.

// userstory.go
func GetSprints(inputFile []byte) []Sprint {
    f := bytes.NewReader(inputFile)
    csvReader := csv.NewReader(f)

    fmt.Println(csvReader.Read())
    data, err := csvReader.ReadAll()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("No errors reading csv. Data: ", data)

enter image description here


Edit: Added a JSON.parse call on the js

// js
files[0].text().then((x) => {
 var sprints = JSON.parse(GetSprints(x));
   console.log(sprints);
})

and json.Marshal on golang side

// userstory.go
func getSprintsWrapper() js.Func {
    getSprintsFunc := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        b, err := json.Marshal(GetSprints([]byte(args[0].String())))
        if err != nil {
            fmt.Println(err)
        }
        return string(b)
    })
    return getSprintsFunc
}

so now the results can be handled as javascript objects.
enter image description here

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文