我有这样的模板(upload.tmpl.html
):
<html>
<body>
<div class="container">
<ul>
<li>current fileName : {{ .fileName}} </li>
</ul>
</body>
</html>
带有
的处理程序uploadHandler.go
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,
})
}
和ReadCsvFile()
这样的方法:
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"
}
我尝试在模板中显示每行的当前fileName,但是可以将频道绑定到模板中吗?因为以这种方式页面不再加载。
答案 0 :(得分:1)
使用Websockets。以下是一些例子:
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)
}
}
Go中的更多Websockets:golang.org/x/net/websocket