英文:
Programatically fetch macOS Version using golang
问题
我想在golang中获取macOS版本。
基本上想检查macOS是否大于或等于Big Sur。
找到了goInfo包。但它没有提供所需的详细信息。
尝试了syscall包,但该解决方案只适用于Linux。
任何帮助都将不胜感激。
英文:
I want to fetch macOS version in golang.
Basically want to check whether the macOS is >= Big Sur.
Found goInfo package. But it doesn't provide the required details.
Tried syscall package but the solution works only on Linux.
any help is appreciated.
答案1
得分: 2
使用unix.Uname函数来获取darwin的发布版本。根据darwin的发布历史,Big Sur对应的darwin版本是20.x.x
。
以下是示例代码:
package main
import (
"fmt"
"strconv"
"strings"
"golang.org/x/sys/unix"
)
func main() {
var uts unix.Utsname
if err := unix.Uname(&uts); err != nil {
panic(err)
}
sysname := unix.ByteSliceToString(uts.Sysname[:])
release := unix.ByteSliceToString(uts.Release[:])
fmt.Printf("sysname: %s\nrelease: %s\n", sysname, release)
if sysname == "Darwin" {
dotPos := strings.Index(release, ".")
if dotPos == -1 {
fmt.Printf("invalid release value: %s\n", release)
return
}
major := release[:dotPos]
majorVersion, err := strconv.Atoi(major)
if err != nil {
fmt.Printf("invalid release value: %s, %v\n", release, err)
return
}
fmt.Println("macOS >= Big Sur:", majorVersion >= 20)
}
}
在我的计算机上的输出结果为:
sysname: Darwin
release: 22.3.0
macOS >= Big Sur: true
参考资料:https://github.com/golang/go/blob/release-branch.go1.20/src/cmd/internal/osinfo/os_unix.go
英文:
Use unix.Uname to get the release version of darwin. According to the release history of darwin, the corresponding darwin version of Big Sur is 20.x.x
.
See the demo below:
package main
import (
"fmt"
"strconv"
"strings"
"golang.org/x/sys/unix"
)
func main() {
var uts unix.Utsname
if err := unix.Uname(&uts); err != nil {
panic(err)
}
sysname := unix.ByteSliceToString(uts.Sysname[:])
release := unix.ByteSliceToString(uts.Release[:])
fmt.Printf("sysname: %s\nrelease: %s\n", sysname, release)
if sysname == "Darwin" {
dotPos := strings.Index(release, ".")
if dotPos == -1 {
fmt.Printf("invalid release value: %s\n", release)
return
}
major := release[:dotPos]
majorVersion, err := strconv.Atoi(major)
if err != nil {
fmt.Printf("invalid release value: %s, %v\n", release, err)
return
}
fmt.Println("macOS >= Big Sur:", majorVersion >= 20)
}
}
Output on my computer:
sysname: Darwin
release: 22.3.0
macOS >= Big Sur: true
Reference: https://github.com/golang/go/blob/release-branch.go1.20/src/cmd/internal/osinfo/os_unix.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论