可以将 golang 通道绑定到模板中

我有这样的模板(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"

}

我尝试在模板中显示每一行的当前文件名,但是可以像这样将通道绑定到模板中吗?因为这样页面就不再加载了。


偶然的你
浏览 141回答 1
1回答

守着星空守着你

使用网络套接字。这里有些例子:HTML/JavaScript:<script>&nbsp; &nbsp; var ws= new WebSocket("ws://yoursite.com");&nbsp; &nbsp; ws.onmessage = function (event) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(event.data);&nbsp; &nbsp; &nbsp; &nbsp; // $('#your-element').html(event.data);&nbsp; &nbsp; }</script>去网络套接字:func websocketSenderHandler(conn *websocket.Conn){&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; msg := <- globalChannel&nbsp; &nbsp; &nbsp; &nbsp; conn.WriteMessage(websocket.TextMessage, msg)&nbsp; &nbsp; }}Go 中的更多 Websocket:golang.org/x/net/websocket其他示例:https : //github.com/golang-samples/websocket
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go