目标:在浏览器中显示 柱状图
原文中漂亮的代码在图片中,无法复制,自己动手写吧,代码:
package main import ( "net/http" "os" "github.com/go-echarts/go-echarts/charts" ) func main() { http.HandleFunc("/", handler) //exec.Command(`cmd`, `/c`, `start`, `http://localhost:8081`).Start() //windows http.ListenAndServe(":8081", nil) } func handler(w http.ResponseWriter, _ *http.Request) { nameItems := []string{"衣", "食", "住"} bar := charts.NewBar() bar.SetGlobalOptions(charts.TitleOpts{Title: "my示例图"}) bar.AddXAxis(nameItems). AddYAxis("商家A", []int{10, 20, 30}). AddYAxis("商家B", []int{15, 25, 35}) f, _ := os.Create("mybar.html") bar.Render(w, f) }
然而,什么也没显示。最后查看网页源代码,发现有如下两句
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script> <link href="https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" rel="stylesheet">
这两个地址在咱们闭关区域当然访问不了,到github上查了一下,可以修改bar.AssetsHost解决。
首先在go代码目录下建assets子目录,再从网上找到echarts.min.js和bulma.min.css下载到该目录中
修改代码如下:
package main import ( "net/http" "os" "github.com/go-echarts/go-echarts/charts" ) func main() { //静态文件服务 http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets")))) http.HandleFunc("/", handler) //exec.Command(`cmd`, `/c`, `start`, `http://localhost:8081`).Start() //windows http.ListenAndServe(":8081", nil) } func handler(w http.ResponseWriter, _ *http.Request) { nameItems := []string{"衣", "食", "住"} bar := charts.NewBar() bar.SetGlobalOptions(charts.TitleOpts{Title: "my示例图"}) bar.SetGlobalOptions(charts.InitOpts{AssetsHost: "http://localhost:8081/assets/"}) bar.AddXAxis(nameItems). AddYAxis("商家A", []int{10, 20, 30}). AddYAxis("商家B", []int{15, 25, 35}) f, _ := os.Create("mybar.html") bar.Render(w, f) }
成功显示柱状图。
更多样式请参考下面的原文吧。