123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package main
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/shirou/gopsutil/v4/cpu"
- "github.com/shirou/gopsutil/v4/host"
- "github.com/shirou/gopsutil/v4/mem"
- "github.com/shirou/gopsutil/v4/net"
- "github.com/shirou/gopsutil/v4/sensors"
- "regexp"
- "time"
- )
- type NetPortJson struct {
- Name string `json:"name"`
- HardwareAddr string `json:"hardwareAddr"`
- Addrs net.InterfaceAddrList `json:"addrs"`
- }
- type IOCountersStat struct {
- Name string `json:"name"` // interface name
- BytesSent uint64 `json:"bytesSent"` // number of bytes sent
- BytesRecv uint64 `json:"bytesRecv"` // number of bytes received
- }
- func shouldSkipInterface(name string) bool {
- // 使用正则表达式匹配需要跳过的接口名称
- skipPattern := regexp.MustCompile(`^lo|docker|br|蓝牙|Loopback|veth|vEth|VMware`)
- return skipPattern.MatchString(name)
- }
- // 获取主机信息
- func Host(ctx *gin.Context) {
- h, _ := host.Info()
- ctx.JSON(200, h)
- }
- // 获取网卡信息
- func NetPort(ctx *gin.Context) {
- interfaces, _ := net.Interfaces()
- var NetPortJsonRes []NetPortJson
- for _, i := range interfaces {
- if shouldSkipInterface(i.Name) {
- continue
- }
- if i.HardwareAddr == "" {
- continue
- }
- NetPortJsonRes = append(NetPortJsonRes, NetPortJson{
- Name: i.Name,
- HardwareAddr: i.HardwareAddr,
- Addrs: i.Addrs,
- })
- }
- ctx.JSON(200, NetPortJsonRes)
- }
- // 获取温度信息
- func Temperature(ctx *gin.Context) {
- temperatures, err := sensors.SensorsTemperatures()
- if err != nil {
- return
- }
- ctx.JSON(200, temperatures)
- }
- // 带宽信息
- func Bandwidth(ctx *gin.Context) {
- netIO, _ := net.IOCounters(true)
- var NetBandwidth []IOCountersStat
- for _, io := range netIO {
- if shouldSkipInterface(io.Name) {
- continue
- }
- NetBandwidth = append(NetBandwidth, IOCountersStat{
- Name: io.Name,
- BytesSent: io.BytesSent,
- BytesRecv: io.BytesRecv,
- })
- }
- ctx.JSON(200, NetBandwidth)
- }
- func Memory(ctx *gin.Context) {
- v, _ := mem.VirtualMemory()
- ctx.Header("Content-Type", "application/json")
- ctx.String(200, fmt.Sprintf("%v", v.UsedPercent))
- }
- func Cpu(ctx *gin.Context) {
- percent, _ := cpu.Percent(time.Second, false)
- ctx.Header("Content-Type", "application/json")
- ctx.String(200, fmt.Sprintf("%v", percent))
- }
|