接着上一个例子
上一个例子是通过ajax请求函数返回数据
现在改成golang里写内容到本地的status.json里,然后ajax直接读取status.json
知识点
http.HandleFunc绑定文件路径
jQuery的getJson方法
js内容
$(function (){
setInterval(myajax, 2000);
function myajax(){
$.getJSON('/status.json',function(data,status){
if (status == 'success') {
$('#cpu').text("Cpu: "+data.Cpuused+"%")
$('#disk').text("Disk: "+data.Diskused+"% used "+data.Diskfree+"G/"+ data.Disktotal+"G")
$('#mem').text("Memory: "+data.Memused+"% used "+data.Memavailable+"G/"+ data.Memtotal+"G")
$('#net').text("总下载: "+data.Netsend+"G | 总上传: "+data.Netrecv+"G")
$('#speed').text("下载: "+data.Netdown+" | 上传: "+data.Netup)
}
});
};
});
main.go
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"text/template"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
)
type Sys struct {
Cpuused float64
Memused float64
Memavailable float64
Memtotal float64
Disktotal float64
Diskfree float64
Diskused float64
Netsend float64
Netrecv float64
Netup string
Netdown string
}
func index(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html") //找模板
t.Execute(w, nil) //执行模板
}
func main() {
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.HandleFunc("/status.json", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.HandleFunc("/", index) //函数也是一种变量
go setjson(2)//开一个协程,因为主程序不会退出,协程又是死循环,所以协程会一直在执行
http.ListenAndServe(":8082", nil)
}
func toG(i uint64) float64 {
return float64(i) / 1024 / 1024 / 1024
}
func toKB(i uint64) float64 {
return float64(i) / 1024
}
func toMB(i uint64) float64 {
return float64(i) / 1024 / 1024
}
func Decimal(value float64) float64 {
value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
return value
}
func getNetSpeed() (string, string) {
// 读取所有网卡网速
Net, _ := net.IOCounters(true)
// 定义网速保存变量
var rx, tx uint64
// 循环网络信息
for _, nv := range Net {
// 去除多余信息
if "eth0" == nv.Name {
// 加上网速信息
rx += nv.BytesRecv
tx += nv.BytesSent
}
}
// 暂停一秒
time.Sleep(time.Second)
// 重新读取网络信息
Net, _ = net.IOCounters(true)
// 网络信息保存变量
var rx2, tx2 uint64
// 循环网络信息
for _, nv := range Net {
// 去除多余信息
if "eth0" == nv.Name {
// 加上网速信息
rx2 += nv.BytesRecv
tx2 += nv.BytesSent
}
}
// 两次相减
if toKB(rx2-rx) > 1024 || toKB(tx2-tx) > 1024 {
down:= strconv.FormatFloat(toMB(rx2 - rx),'f',2,64)+"MB/S"
up:= strconv.FormatFloat(toMB(tx2 - tx),'f',2,64)+"MB/S"
return down, up
} else {
down:= strconv.FormatFloat(toKB(rx2 - rx),'f',2,64)+"KB/S"
up:= strconv.FormatFloat(toKB(tx2 - tx),'f',2,64)+"KB/S"
return down, up
}
}
func getstatus() Sys {
s := Sys{}
m, _ := mem.VirtualMemory()
c, _ := cpu.Percent(time.Second, false)
d, _ := disk.Usage("/")
n, _ := net.IOCounters(true)
s.Netsend = Decimal(toG(n[1].BytesSent))
s.Netrecv = Decimal(toG(n[1].BytesRecv))
s.Diskused = Decimal(d.UsedPercent)
s.Diskfree = Decimal(toG(d.Free))
s.Disktotal = Decimal(toG(d.Total))
s.Memused = Decimal(m.UsedPercent)
s.Memtotal = Decimal(toG(m.Total))
s.Memavailable = Decimal(toG(m.Available))
s.Cpuused = Decimal(c[0])
s.Netdown, s.Netup = getNetSpeed()
return s
}
func writefile(f string) { //创建文件再写入
filePath := "status.json"
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_SYNC|os.O_TRUNC, 0666)
if err != nil {
fmt.Println("open file err", err)
}
//及时关闭file句柄
defer file.Close()
//写入文件时,使用带缓存的 *Writer
write := bufio.NewWriter(file)
write.WriteString(f)
//Flush将缓存的文件真正写入到文件中
write.Flush()
}
func setjson(t int) {//定时写入json
s:=&Sys{}
for {
time.Sleep(time.Second*time.Duration(t))
*s = getstatus()
d, _ := json.Marshal(s)
writefile(string(d))
}
}