I have the go templates (upload.tmpl.html
) like this :
<html>
<body>
<div class="container">
<ul>
<li>current fileName : {{ .fileName}} </li>
</ul>
</body>
</html>
an handler uploadHandler.go
with
func UploadHandler(c *gin.Context) {
file, header, err := c.Request.FormFile("file-upload")
if err != nil {
log.Fatal("Erreur dans la récupération de fichier")
}
//...
fileName := make(chan string)
go ReadCsvFile(bytes, fileName)
go func() {
for {
log.Info(<-fileName)
}
}()
c.HTML(http.StatusOK, "upload.tmpl.html", gin.H{
"fileName": <-fileName,
})
}
and the ReadCsvFile()
method like that :
func ReadCsvFile(bytesCSV []byte, fileName chan string) {
r := bytes.NewReader(bytesCSV)
reader := csv.NewReader(r)
reader.Comma = ';'
records, err := reader.ReadAll()
if err != nil {
fmt.Println("Error:", err)
return
}
db, _ := databaseApp.OpenDatabase()
defer db.Close()
for _, record := range records {
fileName <- record[0]
product := &em.Product{
Name: record[0],
//...
}
db.Create(product)
}
fileName <- "done"
}
I try to display the current fileName of each line in the template, but it is possible to bind the channel into the template like this ? Because in this way the page does not load anymore.
Use Websockets. Here are some examples:
HTML/JavaScript:
<script>
var ws= new WebSocket("ws://yoursite.com");
ws.onmessage = function (event) {
console.log(event.data);
// $('#your-element').html(event.data);
}
</script>
Go Websockets:
func websocketSenderHandler(conn *websocket.Conn){
for {
msg := <- globalChannel
conn.WriteMessage(websocket.TextMessage, msg)
}
}
More Websockets in Go: golang.org/x/net/websocket
Other Example: https://github.com/golang-samples/websocket
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With