go4webdev

Echarts - An Open Source JavaScript Library

Embed Chart.js in Go

Embedding in Go, means that you embed the files into the executable. I created a folder "mbd" at the same level as main.go (could not use the reserved word "embed" as name). Dowloaded and put Chart.min.js in this folder. Here is the "embed" Go code:

//go:embed mbd/chart.min.js
var chartJS []byte
var tpl *template.Template
                
func init() {
    tpl = template.Must(template.New("").Funcs(template.FuncMap{
        "chart": chart,
    }).ParseGlob("./public/tmpl/*/*.html"))
                
    http.Handle("/img/", http.StripPrefix("/img/", http.FileServer(http.Dir("./public/img"))))
    http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./public/css"))))
    http.Handle("/icn/", http.StripPrefix("/icn/", http.FileServer(http.Dir("./public/icn"))))
    http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./public/js"))))
    http.Handle("/misc/", http.StripPrefix("/misc/", http.FileServer(http.Dir("./public/misc"))))
    http.HandleFunc("/mbd/chart.min.js", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/javascript")
        w.Write(chartJS)
    })
}
      
Add the link to Chart.js in the head tag
</head>
    <script src="/mbd/chart.min.js" type="application/javascript"></script>
</head>
      
Chart.js example