monitor.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/shirou/gopsutil/v4/cpu"
  6. "github.com/shirou/gopsutil/v4/host"
  7. "github.com/shirou/gopsutil/v4/mem"
  8. "github.com/shirou/gopsutil/v4/net"
  9. "github.com/shirou/gopsutil/v4/sensors"
  10. "regexp"
  11. "time"
  12. )
  13. type NetPortJson struct {
  14. Name string `json:"name"`
  15. HardwareAddr string `json:"hardwareAddr"`
  16. Addrs net.InterfaceAddrList `json:"addrs"`
  17. }
  18. type IOCountersStat struct {
  19. Name string `json:"name"` // interface name
  20. BytesSent uint64 `json:"bytesSent"` // number of bytes sent
  21. BytesRecv uint64 `json:"bytesRecv"` // number of bytes received
  22. }
  23. func shouldSkipInterface(name string) bool {
  24. // 使用正则表达式匹配需要跳过的接口名称
  25. skipPattern := regexp.MustCompile(`^lo|docker|br|蓝牙|Loopback|veth|vEth`)
  26. return skipPattern.MatchString(name)
  27. }
  28. // 获取主机信息
  29. func Host(ctx *gin.Context) {
  30. h, _ := host.Info()
  31. ctx.JSON(200, h)
  32. }
  33. // 获取网卡信息
  34. func NetPort(ctx *gin.Context) {
  35. interfaces, _ := net.Interfaces()
  36. var NetPortJsonRes []NetPortJson
  37. for _, i := range interfaces {
  38. if shouldSkipInterface(i.Name) {
  39. continue
  40. }
  41. if i.HardwareAddr == "" {
  42. continue
  43. }
  44. NetPortJsonRes = append(NetPortJsonRes, NetPortJson{
  45. Name: i.Name,
  46. HardwareAddr: i.HardwareAddr,
  47. Addrs: i.Addrs,
  48. })
  49. }
  50. ctx.JSON(200, NetPortJsonRes)
  51. }
  52. // 获取温度信息
  53. func Temperature(ctx *gin.Context) {
  54. temperatures, err := sensors.SensorsTemperatures()
  55. if err != nil {
  56. return
  57. }
  58. ctx.JSON(200, temperatures)
  59. }
  60. // 带宽信息
  61. func Bandwidth(ctx *gin.Context) {
  62. netIO, _ := net.IOCounters(true)
  63. var NetBandwidth []IOCountersStat
  64. for _, io := range netIO {
  65. if shouldSkipInterface(io.Name) {
  66. continue
  67. }
  68. NetBandwidth = append(NetBandwidth, IOCountersStat{
  69. Name: io.Name,
  70. BytesSent: io.BytesSent,
  71. BytesRecv: io.BytesRecv,
  72. })
  73. }
  74. ctx.JSON(200, NetBandwidth)
  75. }
  76. func Memory(ctx *gin.Context) {
  77. v, _ := mem.VirtualMemory()
  78. ctx.Header("Content-Type", "application/json")
  79. ctx.String(200, fmt.Sprintf("%v", v.UsedPercent))
  80. }
  81. func Cpu(ctx *gin.Context) {
  82. percent, _ := cpu.Percent(time.Second, false)
  83. ctx.Header("Content-Type", "application/json")
  84. ctx.String(200, fmt.Sprintf("%v", percent))
  85. }