dpdhf02040 2016-05-03 09:28
浏览 46
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • douyijin7741 2016-05-03 09:43
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog