实现方式
在源代码的开头第一行指定需要编译的平台,比如要获取磁盘大小,linux和win 平台的方法是不一样的。注意 编译条件的注释和package 语句之间一定要隔一行。不然无法识别编译条件,编译条件支持“非”逻辑,比如某个文件在非 windows 环境下编译,可以写作
// +build !wiondows
windisk.go
// +build windows
package diskinfo // 注意 编译条件的注释和package 语句之间一定要隔一行。不然无法识别编译条件
import (
"encoding/json"
"fmt"
"io/ioutil"
"os/user"
"runtime"
"syscall"
"unsafe"
"github.com/astaxie/beego/httplib"
"github.com/go-yaml/yaml"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/mem"
"github.com/shirou/gopsutil/net"
)
func getDiskSpace(disks []disk.PartitionStat) ([]restentity.DiskStatus) {
logging.Info.Printf("cuurent os %s", runtime.GOOS)
var diskStatusList []restentity.DiskStatus
kernel32, err := syscall.LoadLibrary("Kernel32.dll")
if err != nil {
logging.Error.Panic(err)
}
defer syscall.FreeLibrary(kernel32)
GetDiskFreeSpaceEx, err2 := syscall.GetProcAddress(syscall.Handle(kernel32), "GetDiskFreeSpaceExW")
if err2 != nil {
logging.Error.Panic(err)
}
lpFreeBytesAvailable := uint64(0)
lpTotalNumberOfBytes := uint64(0)
lpTotalNumberOfFreeBytes := uint64(0)
for _, partion := range disks {
r, a, b := syscall.Syscall6(uintptr(GetDiskFreeSpaceEx), 4,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(partion.Mountpoint))),
uintptr(unsafe.Pointer(&lpFreeBytesAvailable)),
uintptr(unsafe.Pointer(&lpTotalNumberOfBytes)),
uintptr(unsafe.Pointer(&lpTotalNumberOfFreeBytes)), 0, 0)
usedSpace:=lpTotalNumberOfBytes-lpTotalNumberOfFreeBytes
logging.Info.Println("--------------------------------------------")
logging.Info.Println(r, a, b, lpFreeBytesAvailable, lpTotalNumberOfBytes, usedSpace)
logging.Info.Println("--------------------------------------------")
diskStatus := restentity.DiskStatus{
All: lpTotalNumberOfBytes,
Used: usedSpace,
Free: lpFreeBytesAvailable,
Partion: partion,
}
diskStatusList=append(diskStatusList,diskStatus)
}
return diskStatusList
}
linuxdisk.go
// +build linux
// 编译条件支持“非逻辑” +build linux 可以用 +build !windows 替换
package registerservice
func getDiskSpace(disks []disk.PartitionStat) []restentity.DiskStatus {
logging.Info.Printf("cuurent os %s", runtime.GOOS)
var diskStatusList []restentity.DiskStatus
fs := syscall.Statfs_t{}
for _, partion := range disks {
err := syscall.Statfs(partion.Mountpoint, &fs)
if err != nil {
return nil
}
usedSpace := fs.Blocks*uint64(fs.Bsize) - fs.Bfree*uint64(fs.Bsize)
diskStatus := restentity.DiskStatus{
All: fs.Blocks * uint64(fs.Bsize),
Used: usedSpace,
Free: fs.Bfree * uint64(fs.Bsize),
Partion: partion,
}
diskStatusList = append(diskStatusList, diskStatus)
}
return diskStatusList
}
有疑问加站长微信联系(非本文作者)