server.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package utils
  2. import (
  3. "github.com/shirou/gopsutil/cpu"
  4. "github.com/shirou/gopsutil/disk"
  5. "github.com/shirou/gopsutil/mem"
  6. "runtime"
  7. "time"
  8. )
  9. const (
  10. B = 1
  11. KB = 1024 * B
  12. MB = 1024 * KB
  13. GB = 1024 * MB
  14. )
  15. type Server struct {
  16. Os Os `json:"os"`
  17. Cpu Cpu `json:"cpu"`
  18. Rrm Rrm `json:"ram"`
  19. Disk Disk `json:"disk"`
  20. }
  21. type Os struct {
  22. GOOS string `json:"goos"`
  23. NumCPU int `json:"numCpu"`
  24. Compiler string `json:"compiler"`
  25. GoVersion string `json:"goVersion"`
  26. NumGoroutine int `json:"numGoroutine"`
  27. }
  28. type Cpu struct {
  29. Cpus []float64 `json:"cpus"`
  30. Cores int `json:"cores"`
  31. }
  32. type Rrm struct {
  33. UsedMB int `json:"usedMb"`
  34. TotalMB int `json:"totalMb"`
  35. UsedPercent int `json:"usedPercent"`
  36. }
  37. type Disk struct {
  38. UsedMB int `json:"usedMb"`
  39. UsedGB int `json:"usedGb"`
  40. TotalMB int `json:"totalMb"`
  41. TotalGB int `json:"totalGb"`
  42. UsedPercent int `json:"usedPercent"`
  43. }
  44. // InitOS OS信息
  45. func InitOS() (o Os) {
  46. o.GOOS = runtime.GOOS
  47. o.NumCPU = runtime.NumCPU()
  48. o.GoVersion = runtime.Version()
  49. o.NumGoroutine = runtime.NumGoroutine()
  50. return o
  51. }
  52. // InitCPU CPU信息
  53. func InitCPU() (c Cpu, err error) {
  54. if cores, err := cpu.Counts(false); err != nil {
  55. return c, err
  56. } else {
  57. c.Cores = cores
  58. }
  59. if cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true); err != nil {
  60. return c, err
  61. } else {
  62. c.Cpus = cpus
  63. }
  64. return c, nil
  65. }
  66. // InitRAM ARM信息
  67. func InitRAM() (r Rrm, err error) {
  68. if u, err := mem.VirtualMemory(); err != nil{
  69. return r, err
  70. }else {
  71. r.UsedMB = int(u.Used) / MB
  72. r.TotalMB = int(u.Total) / MB
  73. r.UsedPercent = int(u.UsedPercent)
  74. }
  75. return r, nil
  76. }
  77. // InitDisk 硬盘信息
  78. func InitDisk() (d Disk, err error) {
  79. if u, err := disk.Usage("/"); err != nil{
  80. return d, err
  81. } else {
  82. d.UsedMB = int(u.Used) / MB
  83. d.UsedGB = int(u.Used) / GB
  84. d.TotalMB = int(u.Total) / MB
  85. d.TotalGB = int(u.Total) / GB
  86. d.UsedPercent = int(u.UsedPercent)
  87. }
  88. return d, nil
  89. }