相同的代码但使用gin + go-template的结果不同

时间:2015-08-14 08:21:58

标签: html go go-templates go-gin

基本信息

  • Go version:go1.4.2 darwin / amd64
  • 操作系统:Mac OS X 10.10.5

我正在开发一个基于 go gin 编写的小型Web项目。这是我的golang代码。运行go run test.go后,我们有一个Web服务器,正在监听8089。

Golang test.go

package main

import "github.com/gin-gonic/gin"
import "net/http"

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "scheme": "http",
            "domain": "meican.loc",
        })
    })
    router.Run(":8089") // listen and serve on 0.0.0.0:8089
}

后端生成的html代码应该包含前端javascript引擎使用的模板(比方说Angular.js)。

因此,模板代码位于script标记中,如下所示:

模板/ index.html的一部分

<script type="text/template" charset="utf-8">
  <div data="{{.scheme}}://{{.domain}}/qr"></div>
  <div data="{{.scheme}}://{{.domain}}/qr"></div> <!-- problem here -->
</script>

第二次使用{{.domain}}时,我得到了不同的结果。我刷新了浏览器并检查了源代码。然后我明白了:

浏览器源代码结果

<script type="text/template" charset="utf-8">
  <div data="http://meican.loc/qr"></div>
  <div data="http://"meican.loc"/qr"></div>  <!-- problems here -->
</script>

第二个div有两个额外的双引号。

为什么会这样?以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这是Go中的一个错误,截至2016年3月为slated to be fixed in 1.7(1.6中也是partially addressed