You can associate the golang channel with a template
I have go templates ( upload.tmpl.html ):
<html> <body> <div class="container"> <ul> <li>current fileName : {{ .fileName}} </li> </ul> </body> </html> uploadHandler.go handler 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 ReadCsvFile() method:
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 am trying to display the current file name of each line in a template, but can I associate a channel with a template, how is it? Because this way the page no longer loads.
+5
1 answer
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) } } Additional Go sites: golang.org/x/net/websocket
Another example: https://github.com/golang-samples/websocket
+2