Programatically fetch macOS Version using golang

huangapple go评论87阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年4月7日 09:56:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75954946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定